×

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

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.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Implementation of a Falling Matrix in C++

In many Hollywood and Bollywood movies, we might have seen a programmer who will be referred to as a hacker all the time for some random reason which the writer...

3 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Difference between "int main( ) and int main(void)" in C/C++

int main( ) function In the C/C++ programming language, int main() indicates a function that returns an integer at the end of the program execution. In general, a value of '0' indicates...

3 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

Scope Resolution Operator in C++

The scope resolution operator and its different usage in the C++ programming language will be discussed in this section. The scope resolution operator is used to refer to an out-of-scope...

6 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Remove duplicates from sorted array in C++

Remove duplicates from the sorted array in C++. This same process, due to a sorted array, is to erase the redundant components from the array. Examples: Input  : arr[] = {2, 2, 2,...

4 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

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