Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor initialization-list evaluation order

Tags:

c++

c++-faq

gcc

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++

Does order of initializer list matter?

The order of the initializer list does NOT matter. The declaration of your members in the class header defines the initialization order. This is by design and required as you could have multiple ctors having totally different init list orders.

Does initializer list run before constructor?

As already answered, initialization lists get completely executed before entering the constructor block. So it is completely safe to use (initialized) members in the constructor body.

What order is class member data initialized when using constructor initialization lists?

The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon.


It depends on the order of member variable declaration in the class. So a_ will be the first one, then b_ will be the second one in your example.


To quote the standard, for clarification:

12.6.2.5

Initialization shall proceed in the following order:

...

  • 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).

...


The standard reference for this now appears to be 12.6.2 section 13.3:

(13.3) — Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).