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
As JamesKanze has explained, in case of
virtual
inheritance it is the most derived class that calls the virtual base class' constructor. So, if you wantA
's constructor that takes an integer to be called, you need to add that toC
's initialization list.For the second part of your question, default constructors are not required, but then the derived class must call the non-default constructor explicitly, since the compiler is unable to do that for you in the absence of a non-default constructor.
This prints out
There are two questions here.
Because you are using virtual inheritance.
When you use virtual inheritance, the Initialization list of most-derived-class's ctor directly invokes the virtual base class's ctor.. In this case, that means that
C
's constructor callsA
's constructor directly. Since you have not specified whichA
constructor to call inC
's initialization list, the default constructor is called.This is fixed by changing your implementation of
C::C(int)
to:Because
B
also doesn't specify whichA
ctor to call, so the default constructor is used. If you removeA
s def ctor,B
can't be compiled.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.