Will it build an integer array with zero initialization by default?

If I have a structure with an array member and I explicitly call the default constructor of the array in the structure constructor, will the elements be obtained by default? (In the case of an integer array, this would mean getting zero initialization).

struct S { S() : array() {} int array[SIZE]; }; ... S s; // is s.array zero-initialized? 

A quick test with gcc suggests that it is, but I wanted to confirm that I can rely on this behavior.

(I noticed that if I did not explicitly build the default array in the constructor of the structure, the elements of the array have random values.)

+7
source share
1 answer

Yes (emphasis mine):

(C ++ 03 8.5)

To initialize an object of type type T:

  • if T is a class type (section 9) with a constructor declared by the user (12.1), then the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor);

  • if T is a non-unit class of a class without a constructor declared by the user, then each non-static data element and components of the base word T are initialized with a value

  • if T is an array type, then each element is initialized with a value;

  • otherwise the object is initialized to zero

...

An object whose initializer is an empty set of brackets, i.e. (), must be initialized with a value.

+12
source

All Articles