Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization Order of Class Data Members

People also ask

What is the order of initialization for data?

In the initializer list, the order of execution takes place according to the order of declaration of member variables. While using the initializer list for a class in C++, the order of declaration of member variables affects the output of the program. Program 1: C++

Can we initialize data members in a class?

In C++, class variables are initialized in the same order as they appear in the class declaration. Consider the below code. The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.

How do you initialize a class member?

To initialize a class member variable, put the initialization code in a static initialization block, as the following section shows. To initialize an instance member variable, put the initialization code in a constructor.


The order is the order they appear in the class definition - this is from section 12.6.2 of the C++ Standard:

5 Initialization shall proceed in the following order:

— First, and only for the constructor of the most derived class as described below, virtual base classes shall be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base class names in the derived class base-specifier-list.

— Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

— Then, nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

— Finally, the body of the constructor is executed. [Note: the declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. ]


Initialization is always in the order that the class members appear in your class definition, so in your example a, then b.

There is a sequence point between the initialization of each member and you can pass a reference to a yet-to-be initialized member into the constructor of a class member but you would only be able to use it in limited ways (such as taking its address to form a pointer), other uses may well cause undefined behaviour.

Destruction of class members always happens in the reverse order of construction.

Order of initialization of bases and members is defined in 12.6.2 [class.base.init]/5.