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?
Syntax: Class_Name obj[ ]= new Class_Name[Array_Length]; For example, if you have a class Student, and we want to declare and instantiate an array of Student objects with two objects/object references then it will be written as: Student[ ] studentObjects = new Student[2];
In this article we will see that how we can create arrays of custom types. We can achieve it by using custom types. We all know that array is a reference type i.e. memory for an array is allocated in a heap. Sometimes we need to declare arrays of custom types rather than arrays of predefined types ( int or string etc).
Syntax: ClassName ObjectName[number of objects]; The Array of Objects stores objects. An array of a class type is also known as an array of objects.
We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.
You have to provide a default constructor. While you're at it, fix your other constructor, too:
class Name
{
public:
Name() { }
Name(string const & f, string const & l) : first(f), last(l) { }
//...
};
Alternatively, you have to provide the initializers:
Name arr[3] { { "John", "Doe" }, { "Jane", "Smith" }, { "", "" } };
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:
std::vector<Name> arr;
arr.reserve(3); // morally "an uninitialized array", though it really isn't
arr.emplace_back("John", "Doe");
arr.emplace_back("Jane", "Smith");
arr.emplace_back("", "");
std::vector<Name> brr { { "ab", "cd" }, { "de", "fg" } }; // yet another way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With