If myClass does not have a constructor the following works fine:
This is if your class has no user-declared constructor. In that case it has an implicitly-declared default constructor, which is what will be used by
myClass x[5];
to construct the objects.
If you declare a constructor yourself, the implicit default constructor will not be declared. Instead you can declare your own. A default constructor is just a constructor that can be called without arguments:
class myClass {
public:
myClass() {
// Default constructor
}
};
or, if you just want the default constructor to behave exactly as the implicit one would, you can default it:
class myClass {
public:
myClass() = default;
};
If you don't want to do that and use a different constructor, you may still be able to use list initialization:
myClass x[5] = {{/*constructor arguments for first object*/},
{/*constructor arguments for second object*/},
//...
};
Or, easier, just use std::vector<myClass>
and push_back
or emplace_back
each element with the constructor arguments that you need.
std::vector<myClass> x;
x.emplace_back(/*constructor arguments for first object*/);
x.emplace_back(/*constructor arguments for second object*/);
//...
which can also be done in a loop, or, if all all objects are supposed to be copies of one another:
std::vector<myClass> x(5, myClass(/*constructor arguments*/));