Cpp Tutorial: Virtual Base Class and Virtual Inheritance in C++

In this chapter we shall learn about below topics:
1. What is the need of Virtual Base class?
2. How can we solve Diamond Problem with help of Virtual Base class.

What is the need of Virtual Base Class?

Consider the below program that is having a Diamond Problem.
Here derived class “DerivedClass_3” is derived from “DerivedClass_2” and “DerivedClass_1”. Those 2 classes are child of single base class “BaseClass”.
Because of this, “DerivedClass_3” will have multiple copies of data members and member functions from “BaseClass”. This will create ambiguity problem when you try to use data member or member function from base class. Because, as you have 2 copies from the same class, compiler will throw an error.
Diamond Problem representation:
Diamond Problem
Example for Diamond Problem:
#include <iostream> 
using namespace std; 
  
class BaseClass 
{ 
public: 
    void display() 
    { 
        cout << "display from Base Class\n"; 
    } 
}; 
  
class DerivedClass_1 : public BaseClass  
{ 
}; 
  
class DerivedClass_2 : public  BaseClass 
{ 
}; 
  
class DerivedClass_3 : public DerivedClass_1, public DerivedClass_2
{ 
}; 
  
int main() 
{ 
    DerivedClass_3 d3; 
    d3.display(); 
}
Output:
jdoodle.cpp: In function ‘int main()’:
jdoodle.cpp:28:8: error: request for member ‘display’ is ambiguous
   28 |     d3.display();
      |        ^~~~~~~
jdoodle.cpp:7:10: note: candidates are: ‘void BaseClass::display()’
    7 |     void display()
      |          ^~~~~~~
jdoodle.cpp:7:10: note:                 ‘void BaseClass::display()’

As you can see from the output above, we got an ambiguity error. The compiler is not able to decide which display function to call as there are 2 copies of it.

We can solve this problem with help of Virtual Inheritance or Virtual Base Class.

Syntax for Virtual Inheritance:

class DerivedClass_1: virtual public BaseClass
{

}

class DerivedClass_2: virtual public BaseClass
{

}

Note the “virtual” keyword before “public” keyword.
By doing so, compiler will make sure to include only 1 copy of base class data member and member function and thus solving the Diamond Problem.

Example for Virtual Base Class/ Virtual Inheritance

#include <iostream> 
using namespace std; 
  
class BaseClass 
{ 
public: 
    void display() 
    { 
        cout << "display from Base Class\n"; 
    } 
}; 
  
class DerivedClass_1 : virtual public BaseClass  
{ 
}; 
  
class DerivedClass_2 : virtual public  BaseClass 
{ 
}; 
  
class DerivedClass_3 : public DerivedClass_1, public DerivedClass_2
{ 
}; 
  
int main() 
{ 
    DerivedClass_3 d3; 
    d3.display(); 
}

Output:

display from Base Class
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *