William Thomas William Thomas - 2 months ago 7
C++ Question

Initializing and Constructing Arrays of Objects in C++

When declaring an array of objects, are all the objects constructed at initialization, or do they have to be constructed after initialization? Here is an example of what I am trying to explain:

Lets say I have this class:

class Object{
public:
int x = 4;
};


And this array:

Object objects[8];


If I was to access any of the variables within the objects, would I have to construct the objects first, or was that done in the array? So if I did this:

cout << objects[4].x;


Would it print out 4?

Answer

In C++11 your code is perfectly valid, it performs in-class initialization, and indeed, cout << objects[4].x; will print out 4. In previous C++ versions (C++98/03), the code is invalid, and you'd need a default constructor to initialize the variable x, like

class Object{
public:
    int x;
    Object(int x = 4): x(x){}
}
Comments