Everything You Need to Know About a Virtual Base Class in C++

Ever wondered what virtual base classes are? You can use them in virtual inheritance in a technique of checking multiple “instances” of a specified class looking in an inheritance hierarchy through multiple inheritances. When you use multiple inheritances, a virtual base class in C++ is used to avoid multiple "instances" of a given class from occurring in an inheritance hierarchy. 

Now, in this article, you will explore the virtual base class in C++ as a whole. Consider the case where there is just one class A. Two other grades, B and C, descend from this class A.

Virtual_Base_Class_In_C_P_P_1

The data members/functions of class A are inherited twice to class D, as seen in the diagram. The first will take you through class B, and the second will take you through class C. When an object of class D accesses any data or function member of class A, it's unclear which data or function member would be named. One was inherited via B, and it inherited the other via C. This throws the compiler into a loop and causes an error to appear.

Example:

#include <iostream>

using namespace std;

class A {

   public:

   int a;

   A(){

      a = 10;

   }

};

class B : public virtual A {

};

class C : public virtual A {

};

class D : public B, public C {

};

int main(){

   //creating class D object

   D object;

   cout << "a = " << object.a << endl;

   return 0;

}

Output

Virtual_Base_Class_In_C_P_P_2

Stand Out From Your Peers this Appraisal Season

Start Learning With Our FREE CoursesEnroll Now
Stand Out From Your Peers this Appraisal Season

Need for Virtual Base Classes

A virtual base class in C++ is a base class member function you redefine in a derivative class. The interactive keyword is used to declare it.

It tells the compiler whether the feature should be dynamically linked or late-bound.

The use of a single pointer to refer to all the objects of the virtual base class in C++ is needed. As a result, you construct a pointer to the base class that references all derived objects. When the address of the derived class object is contained in the base class pointer, they still execute the base class operation. The only way to solve this problem is to use the 'virtual function.

Rules:

  • The virtual base class in C++ must belong to a certain class
  • Static participants can't be virtual features
  • Object pointers are used to access them
  • They may be classmates from another class
  • Even if it isn't used, it must specify a virtual function in the base class
  • The prototypes of all derived classes and the base class's synthetic functions must be similar. C++ can declare two functions of the same name but separate prototypes to be overloaded functions
  • A virtual function Object() { [native code] } is not possible, but a virtual destructor is
  • Consider what happens if the simulated keyword isn't included

Example: 

#include <iostream>  

using namespace std;  

class A  

{  

   int x=5;  

    public:  

    void display()  

    {  

        std::cout << "Value of x is : " << x<<std::endl;  

    }  

};  

class B: public A  

{  

    int y = 10;  

    public:  

    void display()  

    {  

        std::cout << "Value of y is : " <<y<< std::endl;  

    }  

};  

int main()  

{  

    A *a;  

    B b;  

    a = &b;  

   a->display();  

    return 0;  

}  

Output:

Virtual_Base_Class_In_C_P_P_3

A Pure Virtual Function

A virtual base class in C++ isn't used to do anything. It's just there to be used as a placeholder.

The term "do-nothing" function refers to a function that has no definition.

A pure virtual function is a function that does nothing. Here, you declare a pure virtual function in the base class but do not have a description in the base class.

Abstract base classes are classes that hold a pure virtual purpose but cannot be used to declare objects of their own.

The primary goal of the virtual base class in C++ is to provide attributes to derived classes and to create the base pointer that allows for runtime polymorphism.

How to Resolve This Issue?

When both class B and C inherit class A, the discrepancy is resolved by declaring it as a virtual base class in C++ with the keyword virtual class as:

Class C and B will now have just one copy of the data/function member, and class A will become the virtual base class.

In class hierarchies that use multiple inheritances, virtual base classes have a way to conserve space and prevent ambiguity. When a virtual base is defined, it can serve as an indirect base several times without duplicating the data members. Both base groups that use virtual base share a single copy of the data members.

Example:

#include <iostream>

using namespace std;

class A {

public:

    int a;

    A() // constructor

    {

        a = 10;

    }

};

class B : public virtual A {

}; 

class C : public virtual A {

}; 

class D : public B, public C {

}; 

int main()

{

    D object; // object creation of class d

    cout << "a = " << object.a << endl;  

    return 0;

}

Output:

Virtual_Base_Class_In_C_P_P_4

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

The Syntax for Virtual Base Classes

Instead of writing entirely new data members and member functions while constructing a class, the programmer may specify that the new virtual base class in C++ can inherit the members of an existing class. The original class is known as the base class, while the current class is known as the derived class.

It may descend a class from various base classes or interfaces, allowing it to inherit data and functions from multiple sources.

Syntax 1:

class B : virtual public A 

{

};

Syntax 2:

class C : public virtual A

{

};

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

This was a quick guide to help you understand the basic concepts related to the virtual base class in C++. Want to learn the subject in detail? Then you must enroll in the Simplilearn's Full Stack Development course. Also, for a complete understanding of the subject professionally you must learn it by getting through a skill-up course

After finishing this article, you can develop detailed information of the virtual base class in C++ that permits you to complete operations with classes and objects that you never knew occurred.

Have any questions for us? Leave them in the comments section of this article. Our experts will get back to you on the same, ASAP!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.