Cpp Tutorial: Virtual Base Class in C++

In this chapter we shall see what is virtual base class and why we need virtual base class?

We are aware of diamond problem in C++

#include<iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

class A { 
public: 
    void display() 
    { 
        cout << "Hello form A \n"; 
    } 
}; 
  
class B : public A { 
}; 
  
class C : public A { 
}; 
  
class D : public B, public C { 
}; 
  
int main() 
{ 
    D object; 
    object.display(); 
}

Output:

Error:

Main.cpp:25:12: error: non-static member 'display' found in multiple base-class subobjects of type 'A':
    class D -> class B -> class A
    class D -> class C -> class A
    object.display(); 
           ^
Main.cpp:7:10: note: member found by ambiguous name lookup
    void display()

We get this error because, the function “display()” is inherited 2 times. First from the Class B and another from Class C.
Hence the compiler is confused from which class the display function to be called.

This is diamond problem in C++.

To prevent this problem we need to use “virtual base class”.

Syntax for virtual base class:

Syntax 1:

class Derived : virtual public Base
{
};

Syntax 2:

class Derived: public virtual Base 
{
};

Now we shall modify the above example to inherit the base class as virtual:

#include<iostream>
//for more C++ tutorial visit www.ProDeveloperTutorial.com
using namespace std;

class A { 
public: 
    void display() 
    { 
        cout << "Hello form A \n"; 
    } 
}; 
  
class B : virtual public A { 
}; 
  
class C : public virtual A { 
}; 
  
class D : public B, public C { 
}; 
  
int main() 
{ 
    D object; 
    object.display(); 
}

Output:

Hello form A

So this is the concept of virtual base class.

Write a Comment

Leave a Comment

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