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

Leave a Comment