Order of constructor call in virtual inheritance

Kunal picture Kunal · May 10, 2012 · Viewed 7.9k times · Source
class A {
        int i;
public: 
        A() {cout<<"in A's def const\n";};
        A(int k) {cout<<"In A const\n";  i = k; }
        };

class B : virtual public A {
public:
        B(){cout<<"in B's def const\n";};
        B(int i) : A(i) {cout<<"in B const\n";}
        };

class C :   public B {
public:
        C() {cout<<"in C def cstr\n";}
        C(int i) : B(i) {cout<<"in C const\n";}
        };

int main()
{
        C c(2);
        return 0;
}

The output in this case is

in A's def const
in B const
in C const

Why is this not entering into in A const

`It should follow the order of 1 arg constructor call. But what actually is happening on deriving B from A using virtual keyword.

There are few more question

Even if I remove the virtual keyword in above program and remove all the default constructor it gives error. So, why it needs the def constructor

Answer

James Kanze picture James Kanze · May 10, 2012

The constructors for virtual base classes are always called from the most derived class, using any arguments it might pass in. In your case, the most derived class doesn't specify an initializer for A, so the default constructor is used.