Initialization Order of Class Data Members

Nikhil picture Nikhil · Apr 19, 2010 · Viewed 25.5k times · Source

In the following code, when the ctor of X is called will the ctor of A or B be called first? Does the order in which they are placed in the body of the class control this? If somebody can provide a snippet of text from the C++ standard that talks about this issue, that would be perfect.

class A {};
class B {};
class X
{
 A a;
 B b;
};

Answer

anon picture anon · Apr 19, 2010

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. ]