Search for Courses, Topics
certificate icon
Certificate

Learn on Scaler Topics and get certified.

static-certificate

Virtual Base Class in C++

Learn about Virtual Base Class in C++.

19 Nov 2021-6 mins read
quiz
Challenge Inside! : Find out where you stand! Try quiz, solve problems & win rewards!

Overview

Virtual base classes in C++ are used as a way of preventing multiple instances of a given class from appearing in an inheritance hierarchy when using multiple inheritances.

Scope

  • This article covers the concept of Virtual Base Class in C++.
  • It also covers the concept of Pure Virtual Function in C++.

Introduction to Virtual Base Class in C++

Before getting into virtual base classes, let us revise the concepts of base class and inheritance.

Base classes are the classes from which other classes are derived. The derived(child) classes have access to the variables and methods/functions of a base(parent) class. The entire structure is known as the inheritance hierarchy.

Virtual Class in C++

Let us consider the above image, Class A is the parent class, and Classes B and C are the derived classes from Class A. Thus Class B and Class C have all the properties of Class A.

Next, Class D inherits Class B and also inherits Class C. With our knowledge Class D will get all the properties from Class B and C which also has Class A’s properties in them. What do you think will happen when we will try to access Class A’s properties through D? There will be an error because Class D will get Class A’s properties twice and the compiler couldn’t decide what to output. You’ll see the term “ambiguous” when such a situation occurs.

What is Virtual Class?

Virtual Class is defined by writing a keyword “virtual” in the derived classes which allows only one copy of data to be copied to Class B and Class C (referring to the above example). It is a way of preventing multiple instances of a class appearing as a parent class in inheritance hierarchy when multiple inheritances are used.

Need for Virtual Base Class in C++

In order to prevent the error and let the compiler work efficiently, we’ve to use a virtual base class when multiple inheritances occur. It saves space and avoids ambiguity.

When a class is specified as a virtual base class, it prevents duplication of its data members. Only one copy of its data members is shared by all the base classes that use the virtual base class.

If a virtual base class is not used, then all the derived classes will get duplicated data members. In this case, the compiler cannot decide which one to execute.

Let us look at an example without a virtual base class in C++ and see what the output looks like:

#include <iostream>
using namespace std;

class A {
  public:
    void display() {
      cout << "Hello form Class A \n";
    }
};

class B: public A {
};

class C: public A {
};

class D: public B, public C {
};

int main() {
  D object;
  object.display();
}

Output:

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();
           ^
note: member found by ambiguous name lookup
    void display()
         ^
1 error generated.

In the above example, we create a Class A and then two of its derived classes Class B and Class C. Class A has a method that prints out a statement. All the derived classes must have inherited data members from Class A.

Next, we declare Class D which inherits class B and class C. Since Classes, B and C are child classes of A and then D is the child class of B and C, Class D inherits data members of Class A from both B and C. Hence, duplication occurs and the compiler doesn’t know what to execute and throws an error.

But this situation is avoided if the virtual base class is used.

How to Declare Virtual Base Class in C++?

Syntax

If Class A is considered as the base class and Class B and Class C are considered as the derived classes of A.

Note: The word “virtual” can be written before or after the word “public”.

class B: virtual public A {
  /statement 1
};
class C: public virtual A {
  /statement 2
};

Let us see an example:

#include <iostream>
using namespace std;

class A {
  public:
    int number;
    A() // constructor
    {
      number = 5;
    }
};

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 << " number = " << object.number << endl;

  return 0;
}

Output:

number = 5

In this case, we are using a virtual base class in C++ and so only one copy of data from Class A was inherited to Class D and hence the compiler will be able to print the output.

When we mention the base class as virtual, we avoid the situation of duplication and let the derived classes get only one copy of data.

A Pure Virtual Function

A pure virtual function is a function that does nothing which means that you can declare a pure virtual function in the base class that does not have a description in the base class.

Let’s take an example of a class Animal(base class) that doesn’t have an implementation of moving but all the animals(derived classes) must know how to move considering that all animals can move.

Syntax for Pure Virtual Function C++

class Animal {
  public:
    //Pure Virtual Function
    virtual void move() = 0;
};

Let’s see an example using pure virtual function:

#include <iostream>
using namespace std;

class Animal {
  public:
    //Pure Virtual Function
    virtual void move() = 0;
};

class Lion: public Animal {
  public: 
    void move() {
      cout << "Lions walk in an unusual manner." << endl;
    }
};

class Wolf: public Animal {
  public: 
    void move() {
      cout << "Wolves can move for hours at a speed of 5-6 miles per hour." << endl;
    }
};

int main() {
  Lion l;
  Wolf w;

  l.move();
  w.move();
}

Output:

Lions walk in an unusual manner.
Wolves can move for hours at a speed of 5-6 miles per hour.

In this example, we have created a base class Animal, which consists of a Pure Virtual Function named move(). Next, we have created two derived classes of the base class Animal, namely Lion and Wolf. Now, since we have declared a pure virtual function in our base class Animal, it is necessary to define the function move() in our derived classes, Lion and Wolf.

Conclusion

  • The article covers all the aspects of Virtual Base Class in C++ and its properties. It’ll provide you with a simple explanation with the help of a source code and its output. It is used in the base class in order to ensure that the function is overridden.

  • This article covers all the aspects of Pure Virtual Function in C++ with an example of Animal Base Class.

That’s all for now folks!

Thanks for reading.

Challenge Time!

quiz Time to test your skills and win rewards! Note: Rewards will be credited after the next product update.