DEV Community

Amod Nazirkar
Amod Nazirkar

Posted on

2 2

Virtual base class in c++

Introduction

Let’s start with an example of the hybrid inheritance, in which there is a base class, let's say A, and it has two derived classes, let's say class B and class C. Now as there is hybrid inheritance so there may be another class, let’s say D which inherits properties of both class B and class C.

As a child class can access the member functions or properties of the parent class or even the properties of the parent class’s parents which implies D can access the member functions of its parents B and C, also there parent A. But the problem is A is the parent of both B and C so there are two ways for objects of class D to access the properties of A either via class B or via class C. When a function call is made from object of class D to the function of class A then the compiler will get confused about the path to approach class A this leads to an error.

Let’s see the code of above defined scenario

#include <bits/stdc++.h>
using namespace std;
// defining class A
class A 
{
public:
    void hello_A()
    {
        cout<<"This is class A"<<endl;
    }
};

// defining class B
// class B inherits from class A
class B : public A
{
public:
    void hello_B()
    {
        cout<<"This is class B"<<endl;
    }
};

// defining class C
// class C inherits from class A
class C : public A
{
public:
    void hello_C()
    {
        cout<<"This is class C"<<endl;
    }
};

// defining class D
// class D inherits from both class B and C
class D : public B, public C
{
public:
    void hello_D()
    {
        cout<<"This is class D"<<endl;
    }
};

int main()
{
    // creating the object of class D
    D obj; 

    // calling the function of the class A using object of class D
    obj.hello_A();
}
Enter fullscreen mode Exit fullscreen mode

Error

HelloWorld.cpp: In function 'int main()':
HelloWorld.cpp:52:9: error: request for member 'hello_A' is ambiguous
     obj.hello_A();
         ^~~~~~~
HelloWorld.cpp:7:10: note: candidates are: void A::hello_A()
     void hello_A()
          ^~~~~~~
Enter fullscreen mode Exit fullscreen mode

We get an ambiguous error here as the compiler has no idea which path it has to choose to reach class A. This problem is known as diamond problem, when there is diamond-like shape in our hybrid inheritance then there will be ambiguous error and to remove this error we define the parent class as the virtual class with the help of virtual keyword which means virtual base class is a way of defining virtual inheritance to prevent the multiple instances of a class.

How to declare virtual base class in C++?

Virtual base class is declared with the help of the virtual keyword.

Syntax

Syntax 1: Adding virtual keyword before public keyword

class child_class : virtual public parent_class 
{
};

Syntax 2: Adding virtual keyword after public keyword

class chid_class : public virtual parent_class
{
};
Enter fullscreen mode Exit fullscreen mode

In the above syntax we defined a child class which inherits from the parent class public members and to make it virtual base class we just added virtual keyword by two ways either before public keyword or before access specifier or we can define it after access specifier as we have done in second syntax.

Let’s implement our above code by declaring class A as virtual parent class

#include <bits/stdc++.h>
using namespace std;
// defining class A
class A 
{
public:
    void hello_A()
    {
        cout<<"This is class A"<<endl;
    }
};

// defining class B
// class B inherits from class A
class B : virtual public A
{
public:
    void hello_B()
    {
        cout<<"This is class B"<<endl;
    }
};

// defining class C
// class C inherits from class A
class C : public virtual  A
{
public:
    void hello_C()
    {
        cout<<"This is class C"<<endl;
    }
};

// defining class D
// class D inherits from both class B and C
class D : public B, public C
{
public:
    void hello_D()
    {
        cout<<"This is class D"<<endl;
    }
};

int main()
{
    // creating the object of class D
    D obj; 

    // calling the function of the class A using object of class D
    obj.hello_A();
}
Enter fullscreen mode Exit fullscreen mode

Output:

This is class A
Enter fullscreen mode Exit fullscreen mode

We rewrite the code explained in the above section, only change is we define the base class (class A) as a virtual class using the virtual keyword while inheriting it in class B and class C that makes our code work properly.

Conclusion

  1. Virtual base class is a way of defining virtual inheritance to prevent the multiple instances of a class.
  2. When there is diamond-like shape in hybrid-inheritance, then there is a chance to get errors which can be prevented by declaring base class as virtual.
  3. To declare a virtual class, a virtual keyword is used while inheriting it in child class.
  4. To discover the virtual-base-class topic covered in detail please refer to this Scaler link.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (2)

Collapse
 
vineetjadav73 profile image
vineetjadav

I'm glad I chose this data science course in Bengaluru. The instructors are industry experts, and the practical projects helped me build a strong portfolio.

Collapse
 
pauljlucas profile image
Paul J. Lucas

You didn't mention one of the important things about virtual bases classes in that the most derived class must explicitly call the virtual base constructor (something that non-virtual inheritance doesn't allow — assuming the base class has and you want to call a non-default constructor).

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay