C++: Construction and initialization order guarantees
In all classes construction order is guaranteed: base classes, as specified from left to right followed by member variables in the order declared in the class definition. A class's constructor body is executed once all of its bases' and members' constructions have completed.
In your example X
is derived from Z
and contains Y
so the Z
base object is constructed first, then the Y
member y
, then the construction of the X
completes with the execution of X
's constructor body.
The temporary W
is needed to pass to the constructor of X
, so it is constructed before the construction of the x
begins and will be destroyed once the initialization of x
completes.
So the program must print:
W
Z
Y
X
1) First of all, it is needed to calculate the arguments.
2) Then base classes are constructed.
3) Then members are constructed in the order of appearance in the declaration of the class.
4) Then Constructor of X is called
- The W object will be constructed before the constructor to X is called.
- Z, as a base class of X, will be initialized before the members of X.
- Y will be initalized during member initialization
- X's constructor will run.