I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X
, Y
, Z
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
To expand on Charles Bailey's answer, the rules change when your base classes are inherited virtually. I always forget what the order is, the IBM site says that virtual bases are initialized first but I've just never run into a case where it's actually more than trivia.
To summarize these are the rules:
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