Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual Inheritance, one class enough?

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

like image 715
Invalid Avatar asked Dec 06 '12 21:12

Invalid


2 Answers

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:

inheritance

Why you want to do this is another matter.

like image 148
Ed Heal Avatar answered Oct 14 '22 18:10

Ed Heal


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.

class B { /* ... */ };
class X : virtual public B { /* ... */ };
class Y : virtual public B { /* ... */ };
class Z : public B { /* ... */ };
class AA : public X, public Y, public Z { /* ... */ };

For an object of class AA, all virtual occurrences of base class B in the class lattice of AA correspond to a single B subobject within the object of type AA, and every other occurrence of a (non-virtual) base class B in the class lattice of AA corresponds one-to-one with a distinct B subobject within the object of type AA. Given the class AA defined above, class AA has two subobjects of class B: Z’s B and the virtual B shared by X and Y, as shown below.

virtual inheritance example

like image 30
Billy ONeal Avatar answered Oct 14 '22 18:10

Billy ONeal