How default constructor of most base class is getting called in private virtual inheritance while creating object of most derived class. But the same does not get called when mentioned in constructor initializer list of most derived class.
#include<iostream>
using namespace std;
class A
{
public:
A() {cout << "1";}
};
class B: private virtual A
{
public:
B() {cout << "2";}
};
class C: private virtual A
{
public:
C() {cout << "3";}
};
class D: private B, private C
{
public:
D() : A(), B(), C() {cout << "4";}
//D() {cout << "4";}
};
int main()
{
D d1;
cout << "\n";
}
My Problem:
For Below mentioned code
D() : A(), B(), C() {cout << "4";}
I get below compilation error:
error: 'class A A::A' is inaccessible within this context
Why A() constructor is inaccessible here?
On the other hand below mentioned code gets compiled successfully and A() constructor gets called.
D() {cout << "4";}
Output of the program is:
1234
Means A() constructor is getting called.
So, Why is the change in behavior for calling of constructor A() in above two cases?
What I know:
(1) When I do 'Public Virtual inheritance' of B & C, then default constructor of most base class is gets called even if it's in mentioned in constructor initializer list of most derived class. Means below statement compiles. D() : A(), B(), C() {cout << "4";}
(2) In virtual Inheritance, constructor of virtual base class is called directly from most derived class's constructor.
It might be a concept issue for me of virtual inheritance. Kindly help me to understand this and share good references for that.