Virtual Inheritance, one class enough?

只愿长相守 提交于 2019-12-09 15:21:58

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13752482/virtual-inheritance-one-class-enough

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!