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 A
s 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++.
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.
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).
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.
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.
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:
- 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).
- The body of the constructor is executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With