×

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A. Then class D will inherit properties from class B and class C. An error will occur when we run the code because class D will have twice the properties of class A. In such a situation, we can use the keyword Virtual.

What is Virtual Class?

A Virtual Class is a keyword used in the derived Class. This keyword ensures that only one copy of the parent class is in the derived Class. This virtual Class helps to reduce the error caused in the above example. Specifying a class as a virtual base class prevents duplication of its data members. This allows all base classes that utilize the virtual base class to share only one copy of all the data members.

Example: Error when Class is inherited twice

#include <iostream>
using namespace std;


class A {
  public:
    A() {
        cout << "Constructor A\n";
    }
    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:

Request for member 'display' is ambiguous
object.display();

Explanation:

In the above code, we have considered 4 classes, class A, class B, Class C, and Class D. If the class B and class c inherit properties from class A. Then class D will inherit properties from class B and class C. When we run the code, the error occurs because class D will have twice the properties of class A.

The syntax for declaring virtual base:

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

Example:

#include <iostream>
using namespace std;


class A {
  public:
    A() // Constructor
    {
        cout << "Hi from Constructor A\n";
    }
};
//Class is inherited using the virtual keyword
class B: public virtual A {
};
//Class is inherited using the virtual keyword


class C: public virtual A {
};


class D: public B, public C {
};


int main() {
  D object; // Object creation of class D.


  return 0;
}

Output:

Virtual base class in C++

Explanation:

In the above example, we created 4 classes, the same as the last example, and we also inherited the classes similar to the last example. But here, we used the virtual keyword, which has created a single copy of class A in Class D. Due to this, no error is generated.

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++

Explanation:

In the above example, we have created four classes A, B, C, and D. Using the virtual keyword, we have inherited the properties of A into B and C. Then we have inherited the B and C properties into D here as we have used the virtual keyword so no duplicate class will be created into D, and no error will have occurred.

  1. To ensure that all base classes are created before their derived classes, virtual base classes are always created before non-virtual base classes.
  2. Objects of classes B and C still have calls to class A, but they are ignored when creating objects of Class D. Objects of classes B and C class have the constructor of class A

Pure Virtual Function: A normal virtual function describes the base class with nothing known as a pure virtual function.

Example:

#include <iostream>
using namespace std;


class Animal {
  public:
    // Pure Virtual Function is created inside the parent class
    virtual void move() = 0;
};


class Lion: public Animal {
  public:
    void move() {
      cout << "Hi from the Lion class" << endl;
    }
};


class Wolf: public Animal {
  public:
    void move() {
      cout << "Hi from the wolf class" << endl;
    }
};


int main() {
  Lion l;
  Wolf w;


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

Output:

Virtual base class in C++

Explanation:

We have inherited the base class properties into the other two classes. In the above example, we have created a parent class, Animal, in this Class we have defined Virtual function which is know as pure virtual. In the above Class, we have defined a pure virtual class, so we need to define the function in the derived classes.


Related Topics

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

How to enter a name in C++

A name is a string or array of characters or letters. The string is one of the most helpful data types offered by the C++ library. A string helps the...

4 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

C++ Identifier

In a program, C++ identifiers relate to the names of variables, functions, arrays, and other user-defined data types that the programmer has developed. They are a prerequisite for learning any...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Hello World Program in C++

The steps for “Hello World” C++ program are as follows: Write a C++ code given below in an editor. Save the file with .cpp Compile the code using C++ compiler or using online...

3 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Hashing in C++

Before understanding hashing, we need to know what the use of hashing is. Let us consider an example of a library which consists of many books.Having many books, searching for...

6 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

C++ Do while loop

In this article, we will discuss the C++ Do-While loop with its syntax, working, key features, algorithm, and examples. Do-While Loop: The do-while loop constitutes a specific style of looping construct in...

5 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

Upcasting and Downcasting in C++

With the help of various examples in the C++ programming language, this section will cover Upcasting and Downcasting. Upcasting and downcasting, on the other hand, are two forms of object typecasting. Consider...

3 minutes read.