Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about order of constructor call and virtual base class

Tags:

c++

c++11

order-of-call.cpp

#include <iostream>

class A
{
public:
    A()
    {
        std::cout << "A" ;
    }

};

class B: public A
{
public:
    B()
    {
        std::cout << "B" ;
    }
};

class C: virtual public A
{
public:
    C()
    {
        std::cout << "C" ;
    }

};

class D: public B, public C
{
public:
    D()
    {
        std::cout << "D" ;        
    }

};


int main()
{
    D d;
    return 0;
}

Compile

g++ order-of-call.cpp -std=c++11

Output

AABCD

Why are the two As together in output?. I was expecting something like ABACD. But if I change inheritance order like this class D: public C, public B, the output is as expected ACABD. Is the order part of standard or is something specific to g++.

like image 762
Vivek Avatar asked Oct 09 '18 13:10

Vivek


People also ask

Why is virtual base class constructor called first?

If a derived class has one virtual base class and other non-virtual base class, then the constructor of the virtual base class will be constructed first even though it appears at second position in the declaration. Then the non-virtual base class constructor is executed.

What is the order of execution base class constructors?

Constructors of Virtual base classes are executed, in the order that they appear in the base list. Constructors of nonvirtual base classes are executed, in the declaration order. Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).

What is the correct order of execution of base and derived class destructors?

Q) In inheritance, order of execution of base class and derived class destructors are. In inheritance, execution order of constructors are always from base to derived and destructors call order is in reverse i.e. from derived to base.

What is the order of constructor and destructor calls?

Answer: C++ constructor call order will be from top to down that is from base class to derived class and c++ destructor call order will be in reverse order.


1 Answers

This makes sense, as virtual base class is constructed before non-virtual base classes. So in your case it is: virtual A, non-virtual A, BCD. If you change the inheritance order it is virtual A, C, non-virtual A, BD. Checkout this: https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.3.0/com.ibm.zos.v2r3.cbclx01/cplr389.htm

The order of initializing class is following:

  1. Constructors of Virtual base classes are executed, in the order that they appear in the base list.
  2. Constructors of nonvirtual base classes are executed, in the declaration order.
  3. Constructors of class members are executed in the declaration order (regardless of their order in the initialization list).
  4. The body of the constructor is executed.
like image 146
bartop Avatar answered Nov 13 '22 09:11

bartop