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.
A
is privately owned byB
andC
,D
cannot access it. It's that simple. – Patrick RobertsA
's constructor is inaccessible becauseD
has not a subclass of typeA
, instead it derives fromB
andC
that derive privately fromA
. The other way around works for you implicitly constructC
andB
and they implicitly constructA
, that is something they are allowed to do being it a direct subclass. – skypjackclass D: virtual private A, private B, private C
– M.MA()
call. It will happen anyway, but at the correct point, and this isn't it. You should only be calling constructors for direct base classes or instance members here. – user207421