I’m trying to declare an array with a custom class. When I added a constructor to the class, my compiler complains that there’s “No matching constructor for initialization of name[3]”.
Here’s my program:
#include <iostream>
using namespace std;
class name {
public:
string first;
string last;
name(string a, string b){
first = a;
last = b;
}
};
int main (int argc, const char * argv[])
{
const int howManyNames = 3;
name someName[howManyNames];
return 0;
}
What can I do to make this run, and what am I doing wrong?
You have to provide a default constructor. While you’re at it, fix your other constructor, too:
Alternatively, you have to provide the initializers:
The latter is conceptually preferable, because there’s no reason that your class should have a notion of a “default” state. In that case, you simply have to provide an appropriate initializer for every element of the array.
Objects in C++ can never be in an ill-defined state; if you think about this, everything should become very clear.
An alternative is to use a dynamic container, though this is different from what you asked for: