C++: Construction and initialization order guarantees

前端 未结 5 449
南笙
南笙 2020-12-03 11:14

I have some doubts about construction and initialization order guarantees in C++. For instance, the following code has four classes X, Y, Z

5条回答
  •  不知归路
    2020-12-03 12:03

    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
    

提交回复
热议问题