0

If myClass does not have a constructor the following works fine:

myClass x[5];

If I put a constructor in myClass this line results in a compiling error.

What is standard practice for creating an array of objects when a constructor is defined?

Is it possible to populate the entire array of objects with a single constructor?

1 Answers1

4

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*/));
user17732522
  • 53,019
  • 2
  • 56
  • 105
  • 1
    The default constructor can also be defined as `myClass() = default;' if the compiler-generated constructor is adequate. +1. – Pete Becker Dec 31 '21 at 23:35