C++: Construction and initialization order guarantees

前端 未结 5 427
南笙
南笙 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 11:45

    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

    0 讨论(0)
  • 2020-12-03 11:50

    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.

    0 讨论(0)
  • 2020-12-03 11:53

    To summarize these are the rules:

    1. Arguments, taken from Right to Left
      a. Right Most
      b. 2nd from Right
    2. Base class
    3. Virtual base
    4. Base classes from Left to Right
    5. Members in Order of Declaration in class
    6. Constructor of called class
    0 讨论(0)
  • 2020-12-03 12:01
    1. The W object will be constructed before the constructor to X is called.
    2. Z, as a base class of X, will be initialized before the members of X.
    3. Y will be initalized during member initialization
    4. X's constructor will run.
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题