Sobes.tech
Middle+

What is virtual inheritance?

sobes.tech AI

Answer from AI

Virtual inheritance is a form of inheritance in C++ that allows avoiding the "diamond problem" when the same base class is inherited indirectly through multiple paths. With virtual inheritance, the shared base class will exist as a single instance within the final class object.

Advantages:

  • Avoids duplication of data and functions from the common base class.
  • Provides a single source for accessing members of the virtual base class.

Disadvantages:

  • Complicates object construction and access to virtual base classes (through "indirect" pointers or offsets).
  • Slightly reduces performance when accessing members of the virtual base class due to the need to resolve offsets at runtime.
  • Restrictions on using virtual base classes in certain contexts (e.g., during static initialization).

It is used when declaring a base class with the virtual keyword.

class Base {
public:
    int data;
};

class Derived1 : virtual public Base { // Virtual inheritance
};

class Derived2 : virtual public Base { // Virtual inheritance
};

class Final : public Derived1, public Derived2 { // Diamond inheritance
};

// In the Final class object, there will be only one instance of Base::data