How to initialize an array of a complex object?

I have:

class SomeObject { public: SomeObject() { ... } // Other fields and methods }; class anOtherObject { private: SomeObject array[SOME_FIXED_SIZE]; public: anOtherObject() : ... { ... } }; 

My question is: what does the array contain when and after the constructor call? should I initialize it myself using a for loop or does the compiler call the default constructor for each array [i], 0<=i<SOME_FIXED_SIZE ?

+6
source share
3 answers

An array is initialized by default, which means that its elements are initialized by default one by one. Since your array contains user-defined types, this means that their default constructor will be called. If built-in types or PODs are stored in your array, you must be explicit and initialize the value, since the default initialization means that the initialization is not performed on the elements:

 anOtherObject() : array() {} // ^^^^^^^ value-initialize array 
+6
source

You do not need to initialize them. Creating an array will be created by default. Unless you explicitly omit the default constructor.

When an array of class objects is initialized (explicitly or implicitly) and the elements are initialized by the constructor, the constructor must be called for each element of the array, following the order of the substring; [ยง12.6 / 3]

0
source

when you create an object of type anOtherObject: anOtherObject a; since object a has a private array of type SomeObject, the default constructor of the SomeObject class is called for each element of the array. Before the constructor is called, the array must contain garbage, as it is statically allocated on the stack. After calling the constructor, the memory should contain everything that you specified in the default constructor; for example, initializing everything to 0

0
source

Source: https://habr.com/ru/post/957824/


All Articles