×

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 an inheritance hierarchy. We can define it as-“A virtual base class is used in C++ to prevent several "instances" of a certain class from existing in an inheritance hierarchy when multiple inheritances are employed.”

Virtual class in C++

Imagine, for instance, that we created a class "A" from which two other classes, "B" and "C," are derived. However, as illustrated in the figure, once a class "D" is created, it is descended from classes "B" and "C."

Class "A" is the parent class of classes "B" and "C."

Additionally, classes "B" and "C" are the parents of class "D."

The most important thing to take away from this is that class "D" will double-inherit the data members and member functions of class "A" because class "B" and class "C" are class "D's parent classes, and both are descended from class "A".

As a result, the compiler will confuse and produce an error if class "D" attempts to access a class "A" member function or data. Therefore, we can create class "A" as a virtual base class to clear this uncertainty. The "virtual" keyword is used to create a virtual base class.

When a class is made virtual, only one copy of its data members and member functions are passed on to the classes that inherit it. Therefore, in our example, if we make class "A" a virtual class, only one copy of the data member and member function will be sent to classes "B" and "C," which will be shared by all classes. By doing this, the uncertainty will be resolved.

What is Virtual Class?

We can define the Virtual class by writing the keyword “Virtual” in the derived class, allowing only one copy of data to be copied to classes B and C. (referring to the above example). When multiple inheritances are used, it prevents several instances of a class from appearing as a parent class in the inheritance tree.

Need of Virtual Base Class:

In C++, a virtual base class is a member function that we redefine in a derivative class. It is declared using the virtual keyword.

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

In C++, a single pointer must be used to refer to all of the objects of the virtual base class. As a result, you create a base class pointer that contains references to all objects that are derived. They nevertheless carry out the base class operation when the address of the derived class object is in the base class pointer. Use of the "virtual function" is the sole solution to this issue.

Rules for Virtual Class

  • In C++, a specific class is required for the virtual base class.
  • Virtual features cannot participate like static participants.
  • Accessing them requires using object pointers.
  • It is necessary for it to provide a virtual function in the base class, even if it isn't used.
  • The synthetic functions of the base class and the prototypes of all derived classes must be equivalent. In C++, two identical functions with different prototypes might be declared to be overloaded functions.
  • A virtual destructor is feasible, but a virtual constructor is not.

How to declare Virtual Base Class:

The programmer may declare that the new virtual base class in C++ can inherit the members of an existing class, saving them from having to be written from scratch when creating a class. The original class is referred to as the base class, while the current class is referred to as the derived class.

It is possible for a class to be derived from different base classes or interfaces, enabling it to inherit information and features from various sources.

If Class X is regarded as the base class and Classes Y and Z as the derived classes from Class X.

Syntax

class Y: virtual public X {
  // Statement For class Y
};
class Z: public virtual X {
  // statement for class Z
};

Pure Virtual Function:

There isn't any use for a virtual base class in C++. The only purpose of it is to serve as a stand-in.

Functions that have no definition are referred to as "do-nothing" functions.

An empty function is referred to as a pure virtual function. The base class, in this case, contains a declaration of a pure virtual function but no description.

It is impossible to declare objects of one's own in abstract base classes because they serve only a pure virtual purpose.

The creation of the base pointer that enables runtime polymorphism is the main function of the virtual base class in C++, along with providing properties to derived classes.

Program

#include<iostream>
using namespace std;


class Scholar{
    protected:
        int roll_no;
    public:
        void fix_number(int x){
            roll_no = x;
        }
        void display_number(void){
            cout<<"Your roll no is "<< roll_no<<endl;
        }
};


class Exam : virtual public Scholar{
    protected:
        float Programming, Data_science;
        public:
            void fix_marks(float y, float z){
                Programming = y;
                Data_science = z;
            }


            void display_marks(void){
                cout << "The outcome is as follows: "<<endl
                     << "Programming: "<< Programming<<endl
                     << "Data_science: "<< Data_science<<endl;
            }
};


class Tournament: virtual public Scholar{
    protected:
        float run;
    public:
        void fix_run(float a){
            run = a;
        }


        void display_run(void){
            cout<<"Your Tournament run is: "<<run<<endl;
        }


};


class Outcome : public Exam, public Tournament{
    private:
        float overall;
    public:
        void print(void){
            overall = Programming + Data_science + run;
            display_number();
            display_marks();
            display_run();
            cout<< "Your overall rating is: "<<overall<<endl;
        }
};


int main(){
    Outcome David;
    David.fix_number(340);
    David.fix_marks(250, 105.5);
    David.fix_run(90);
    David.print();
    return 0;
}

Explanation:

  • Our "Scholar" class has a protected data member named "roll_no" as well as member functions named "fix_number" and "display_number". The protected data member "roll_no" will get a value from the method "fix_number," and the function "display_number" will display that value.
  • A new class called "Exam" that is derived from the virtual base class "Scholar" has been created. The "Exam" is made up of the protected data members "Programming" and "Data_science" as well as the member functions "fix_ marks" and "display_marks". The functions "fix_number" and "display_marks" will assign values to the protected data members "Programming" and "Data_ science," respectively, and print the values of those elements.
  • A new class called "Tournament" has been developed; it is derived from the virtual base class "Scholar." The "Tournament" is made up of the member functions "fix _run" and "display_run" as well as the protected data member "run". The protected data members "run" will have values assigned to them by the function "fix_run," and the function "display_run" will output the value of those data members.
  • A new class called "Outcome" has been created; it inherits from the base classes "Exam" and "Tournament." The "Outcome" is made up of the member functions "print" and the protected data member "overall". In order to assign a value to the protected data members "overall," the function "print" first adds the values of the data members "Programming," "Data_science," and "run." Next, it calls the functions "display_number," "display_marks," and "display_run," and prints the value of the data member "overall."
  • A new "Outcome" object named "David" is generated.
  • The object "David" calls the function "fix number," passing "340" as the parameter.
  • The "David" object calls the "fix marks" function, passing it the values "250" and "105.5".
  • David, an object, calls the function "fix run" with the argument "90."
  • David is the object that calls the function "print."

The crucial point to take up from this is that there won't be any ambiguity because we made the "Student" class a virtual base class, but if we remove the "virtual" term, the comparison will fail.

Program Output:

Virtual class in C++

Conclusion

A virtual class is built in C++ by using the virtual keyword.

The parent class function we wish to redefine in the child class is the virtual function.

All objects of various classes must be referenced by a single pointer.

Run the superclass function at all times using the superclass pointer, which includes the address of the object of the derived class.

The virtual functions must be class members, cannot be declared static, and are only accessible via object references.

A virtual function of a superclass and its child classes should have the same signature, a practice known as function overriding; otherwise, in C++, two functions with the same name but distinct signatures are referred to as overloaded functions.


Related Topics

Bit Manipulation in C++

The high-level language in which we communicate is not understood by the computer. As a result, there existed a standard mechanism for understanding any instruction sent to the computer. At...

5 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

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

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

Random Number Generator in C++

In programming, we need to frequently create the randomly. For example, a dice game, handing out cards to players, apps for rearranging tunes, etc. T There are two tools available in...

4 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

Print Table Using While Loop in C++

Multiplication Table In mathematics, a table is created by multiplying a certain number by all of the counting numbers, i.e., 1, 2, 3, 4, 5, 6, and so on. It is...

4 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.