Confusion about order of constructor call and virtual base class

  • A+
Category:Languages

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++.

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: