Virtual Inheritance in C++ (NC)

Virtual Inheritance

解决菱形继承的代码重复问题。

Virtual Base Class:这是在多重继承中用来避免重复继承的一种机制。假设我们有一个基类A,还有两个从A继承的类B和C。如果再创建一个类D,它同时继承自B和C,那么D将拥有A的两份副本。但在某些情况下,我们只希望有A的一份副本,这时就需要使用virtual base class。

class A {
    // Base class A
};

class B : virtual public A {
    // B is virtually inherited from class A
};

class C : virtual public A {
    // C is also virtually inherited from class A
};

class D : public B, public C {
    // D inherited from B and C
};

Virtual Inheritance是为了实现上面说的virtual base class机制而引入的。通过virtual inheritance,派生类D将只拥有基类A的一份副本,避免了重复继承的问题。这在多重继承层次结构中尤其有用。
Pasted image 20241009225008.png
使用虚继承后,C++会确保无论多少个派生类,它们都共享同一个虚基类实例。编译器会在派生类的vtable中添加指向虚基类的指针,确保正确访问虚基类。

if not using virtual keyword, B and C both will point to their owning entity

points to the same entity using virtual keyword

ambiguous
odr???????

multiple inheritance