Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize array of a complex object?

Tags:

c++

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 array contain when and after the constructor is called? should I initialize it by myself with a for loop or does the compiler call the default constructor for each array[i] , 0<=i<SOME_FIXED_SIZE ?

like image 439
Shmoopy Avatar asked Nov 11 '13 11:11

Shmoopy


1 Answers

The array is default-initialized, which means its elements are default initialized one by one. Since your array holds user defined types, this means their default constructor will be called. If your array held built-in types or PODs, you would have to be explicit and value-initialize it, since default initialization would mean no initialization is performed on the elements:

anOtherObject() : array() {}
//                ^^^^^^^ value-initialize array
like image 156
juanchopanza Avatar answered Oct 21 '22 20:10

juanchopanza