What is the order in which the destructors and the constructors are called in C++

后端 未结 5 1042
执笔经年
执笔经年 2020-12-07 16:48

What is the order in which the destructors and the constructors are called in C++? Using the examples of some Base classes and Derived Classes

5条回答
  •  爱一瞬间的悲伤
    2020-12-07 17:07

    The order is:

    1. Base constructor
    2. Derived constructor
    3. Derived destructor
    4. Base destructor

    Example:

    class B
    {
    public:
      B()
      {  
        cout<<"Construct B"<

    Output of example:

    Construct B

    Construct D

    Destruct D

    Destruct B

    Multiple levels of inheritance works like a stack:

    If you consider pushing an item onto the stack as construction, and taking it off as destruction, then you can look at multiple levels of inheritance like a stack.

    This works for any number of levels.

    Example D2 derives from D derives from B.

    Push B on the stack, push D on the stack, push D2 on the stack. So the construction order is B, D, D2. Then to find out destruction order start popping. D2, D, B

    More complicated examples:

    For more complicated examples, please see the link provided by @JaredPar

提交回复
热议问题