×

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

Different Ways to Compare Strings in C++

This section will go over the many methods for comparing strings in the C++ programming language. The string comparison checks if the first string is equal to another string. HELLO...

6 minutes read.

C++ Friend function

A friend function has the right to access all private and protected members of a class although it is defined outside that class' scope. Syntax class className{     ......     friend retyrn_type function_Name(argument);     .......   }   return_type function_Name(argument){     ......   } C++ friend function Example #include <iostream>   using namespace std;   class Length   {       private:           int meter;       public:           Length(): meter(5) { }           friend int addMethod(Length); //friend function declaration   };   int addMethod(Length l) // friend function definition   {       l.meter += 10; //accessing private data from non-member function       return l.meter;   }   int main()   {       Length L;       int totallength;       totallength=addMethod(L);       cout<<"Length: "<< totallength;       return 0;   } Output: Length: 15   C++ friend function...

1 minute read.

Queue in C++

What is Queue? As the name suggests, the queue is the type of data structure that follows the FIFO (First In - First Out) mechanism. In simple words, it is...

4 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 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.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most...

3 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

4 minutes read.

C++ OOPs Concept

The main goal of C ++ programming is to add the idea of ​​object orientation to the C programming language. Inheritance, data binding, polymorphism and other concepts are part of...

4 minutes read.

C++ Continue in for loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

Classes and Objects in C++

When it comes to object-oriented programming, objects are the basic building blocks. Memory is taken up by objects, which contain data and methods or functions that operate on it. On...

3 minutes read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Floating Point Operations and Associativity in C, C++ and Java

In this tutorial, we are going to compare Floating-point operations and the concept of associativity. Before we apply the concept of associativity in the floating-point operations in all three programming...

3 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.

Decltype type Specifier in C++

The primary use of C++ decltype is to inspect the declaration type of an entity in an expression. The auto keyword can declare a particular type of variable, whereas the...

4 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.