I understand the concept of virtual inheritance, but I couldn't find the answer to this anywhere. Say you have class D which inherits class B and C. Both B and C inherit class A. So you could make B and C virtually inherit A to avoid two instances of A. But do you have to specify virtual inheritance at both B and C or does it already create only one instance of A if one of the two virtually inherits A and the other doesn't?
Thanks
They must all be
virtual
. From C++11 10.1 [class.mi]/7:A class can have both virtual and non-virtual base classes of a given type.
For an object of class
AA
, all virtual occurrences of base classB
in the class lattice ofAA
correspond to a singleB
subobject within the object of typeAA
, and every other occurrence of a (non-virtual) base classB
in the class lattice ofAA
corresponds one-to-one with a distinctB
subobject within the object of typeAA
. Given the classAA
defined above, classAA
has two subobjects of classB
:Z
’sB
and the virtualB
shared byX
andY
, as shown below.You need to specify virtual inheritance for both B and C to have one A. Otherwise the class that is not using virtual inheritance will "share" class A.
This can enable one to have the following:
Why you want to do this is another matter.