I wrote this code so I can understand more about c , I know that I get this warning because of the virtual inheritance in class B and class C is not virtual public inheritance ,and I know that this warning can go if I changed it .
but what I don't understand is : why my code works and why it wont get this warning if I only made this change ---> class C :virtual public A and not made the change for both classes (C and B) :
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A"; }
A(const A&) { cout << "a"; }
};
class B : virtual A
{
public:
B() { cout << "B"; }
B(const B&) { cout << "b"; }
};
class C : virtual A
{
public:
C() { cout << "C"; }
C(const C&) { cout << "c"; }
};
class D :B, C
{
public:
D() { cout << "D"; }
D(const D&) { cout << "d"; }
};
int main()
{
D d1;
D d2(d1);
}
: warning C4594: class 'D' can never be instantiated - indirect virtual base class 'A' is inaccessible
: message : 'A' is a private base class of 'B'
CodePudding user response:
Actually protected
instead of public
would suffice...
Now assume your classes would not inherit virtually.
What now happens is that any instance of B
incorporates its own instance of A
as well as does any instance of C
. Both B
and C
call A
's constructor already, an inheriting class D
doesn't need to care for.
This changes if virtual inheritance is introduced: Now the task of constructing the sole instance of A
is delegated to the most derived class, which is D
in given case.
D
now needs access to this common instance of A
to be able to call it's constructor. This can occur via B
or (!) via C
– so it suffices if at least one of these provides at least protected
access to that single instance – C
in given case but could have been B
as well.