Search code examples
c++arraysvisual-studioruntime-errorobject-initialization

How can I initialize an array of objects?


I've written this code but I have some errors when I try to initialize an array of Critter objects and don't know what they're about.

My code:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Critter {
private:
    string crName;
public:
    Critter(string = "Poochie");
    string getName() const { return crName; }
};

Critter::Critter(string n) {
    crName = n;
}

int main() {
    Critter c[10] = { "bob","neo","judy","patrik","popo" }; //here
    return 0;
}

The errors:

E0415 - no suitable constructor exists to convert from "const char [4]" to "Critter"
...
4 more like this.

This code worked on a friend's Visual Studio 2017, but not in mine which is the 2019 version.

Thanks.


Solution

  • Critter c[10] = { "bob","neo","judy","patrik","popo" };

    This defines an array of const char *. To initialize an array of Critter with those strings, instead:

    Critter c[10] = { {"bob"}, {"neo"}, {"judy"}, {"patrik"}, {"popo"} };


    [ EDIT ] It was pointed out that the same answer was first posted in a comment, only it was hidden in an external link with no indication of what's behind it, which I did not see before posting the above. Credit goes to @drescherjm so I'll leave this here as a CW.