Posted Joe Chu cpp3 minutes read (About 394 words)0 visits
Virtual Inheritance
Solve diamond problem.
1. Introduction
Virtual inheritance is used to solve the diamond problem in multiple inheritance. A typical diamond problem is: when a class inherits two classes that both inherit from a common base class. Without the virtual inheritance, the common base class is duplicated, causing compiler ambiguity when accessing base class members or functions.
1 2 3 4 5 6 7 8
(left) without virtual inheritance (right) with virtual inheritance
A A A | | / \ B C B C \ / \ / D D
2. Examples
2.1 Without virtual inheritance
We keep two instances of base class A. To avoid compiler ambiguity, we need to use scope resolution operator(::) to access a specific instance of A.
intmain(){ D obj; // obj.value; // Error: ambiguous access obj.B::value = 1; // Access value through B's A obj.C::value = 2; // Access value through C's A
Virtual inheritance ensures that there is only one instance of the common base class, shared by all derived classes. A virtual base pointer (vptr) is used to point to the shared instance of the base class.
classA { public: int value; A(int val) : value(val) { std::cout << "A(int) called with val = " << val << std::endl; } };
classB : virtualpublic A { public: B() : A(0) { // Provide a default value to A std::cout << "B() called" << std::endl; } };
classC : virtualpublic A { public: C() : A(0) { // Provide a default value to A std::cout << "C() called" << std::endl; } };
classD : public B, public C { public: D(int val) : A(val), B(), C() { // Initialize A with a specific value std::cout << "D(int) called with val = " << val << std::endl; } };