Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero-Initialize array member in initialization list

Tags:

People also ask

How do you initialize an array with 0?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

Can you initialize an array with 0 elements?

The initializer can even have no values, just the braces: int baz [5] = { }; This creates an array of five int values, each initialized with a value of zero: But, the elements in an array can be explicitly initialized to specific values when it is declared, by enclosing those initial values in braces {}.

Are class members zero initialized?

zero-initialization – Applied to static and thread-local variables before any other initialization. If T is scalar (arithmetic, pointer, enum), it is initialized from 0 ; if it's a class type, all base classes and data members are zero-initialized; if it's an array, each element is zero-initialized.

What is member initialization list?

Member initializer list is the place where non-default initialization of these objects can be specified. For bases and non-static data members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.


I have a class with an array member that I would like to initialize to all zeros.

class X { private:     int m_array[10]; }; 

For a local variable, there is a straightforward way to zero-initialize (see here):

int myArray[10] = {}; 

Also, the class member m_array clearly needs to be initialized, as default-initializing ints will just leave random garbage, as explained here.

However, I can see two ways of doing this for a member array:

With parentheses:

public:     X()     : m_array()     {} 

With braces:

public:     X()     : m_array{}     {} 

Are both correct? Is there any difference between the two in C++11?