Virtual Function in C++

In this blog, we will learn about virtual functions in c++. We will have a proper idea of what a virtual function in c++ is, why we need it, its features and various identifier in it, its uses, and its example with code and explanation followed by pure virtual function with its explanation and its code the description of the code with working.

What is a Virtual Function in C++?

C++ is one of the world’s most used programming languages. The language contains the concept of object-oriented programming or OOps. As it uses oops hence it provides the four pillars of oops i.e, encapsulation, polymorphism, abstraction, and inheritance. And with all these pillars it provides the features and functions of these also one of them is the virtual function.

  • Virtual Function in c++ is the same member function that is defined in the base class as well as a derived class which means the member function is redefined in the derived class.
  • So when you are calling the member function with the help of the pointer of the base class it will call the function of the base class but not of the derived class.
  • Hence we can say that the derived class member function is not overridden.
  • To override the member function of the derived class we use a virtual keyword with the member function of the base class.
  • It is mainly used to achieve run time polymorphism
  • We just need to add a virtual keyword before the normal declaration of the function in the base class.
  • It is used to tell the compiler to perform late binding or dynamic linkage on the function.

Dynamic Linkage or Late Binding
In late binding or dynamic linkage the function is resolved during run time. Therefore at runtime, the compiler determines the type of object., and then binds the function call.

Rules of Virtual Functions

  • The virtual function in c++ cannot be present in any class they need to be a member of the same class. I.e, the base, and derived classes.
  • There is no boundation of being a friend of any class hence they can be a friend of another class also.
  • We can have a virtual destructor but we cannot have a virtual function constructor in c++.
  • We can access virtual functions in c++ with the help of object pointers.
  • Virtual functions in c++ cannot be static members.
  • They are always written in the base class and overridden in the derived class.
  • The name of the member function must be the same in the derived as well as the base class.
  • We have to write the keyword “virtual” before the function declaration in the base class.

Example of the Code without Virtual Function in C++

In the following example, we will look at the function without the use of a virtual function and will see the output and the explanation of the same.

#include <iostream>  
using namespace std;  
class A  
{  
   int x=75;  
    public:  
    void display()  
    {  
        std::cout << "Value of x is : " << x<<std::endl;  
    }  
};  
class B: public A  
{  
    int y = 10;  
    public:  
    void display()  
    {  
        std::cout << "Value of y is : " <<y<< std::endl;  
    }  
};  
int main()  
{  
    A *a;  
    B b;  
    a = &b;  
   a->display();  
    return 0;  
}

Output
The output of the above code will be

Explanation of the Code
In the above code as you can see that we have two classes named A and B class A is the base class whereas class B is the derived class of the base class A. We have the same function named display in both the base and derived class and when we made a pointer of the base class and then call the display function it will call the display function of the base class not of the derived class.

This indicates that the derived class member function is not overridden in this case we can use the virtual function in c++.

As you can see in the output we will get the value of x which is in the base class so to get the value of we will need a virtual function in c++.

Example of Code with Virtual Function in C++

In the following code, we will look at an example where we are using the virtual function to get the member function of the derived class by using the pointer of the base class.

#include <iostream>  
using namespace std;  
class A  
{  
   int x=75;  
    public:  
    void display()  
    {  
        std::cout << "Value of x is : " << x<<std::endl;  
    }  
};  
class B: public A  
{  
    int y = 10;  
    public:  
    void display()  
    {  
        std::cout << "Value of y is : " <<y<< std::endl;  
    }  
};  
int main()  
{  
    A *a;  
    B b;  
    a = &b;  
   a->display();  
    return 0;  
}

Output

Explanation of the above code of virtual function in C++
As you can see in the above code we have written the virtual function with the member function of the base class and not with the member function of the derived class because it is the rule while dealing with the virtual function in c++ that we have to add a virtual keyword before the member function of the base class.
As you can see in the output of the above example that the result is derived class is invoked. Hence the member function of the derived class is overridden.

Working of Virtual Functions in C++

As we have already mentioned that compiler deals with virtual functions so the compiler performs two functions on priority that is:

  1. A virtual pointer (VPTR) is inserted as a class data member to point to the class’s VTABLE whenever an object of that class is created. A new virtual pointer is added as a data member of that class for each new object produced.
  2. VTABLE, a static array of function pointers, is a member of the class regardless of whether an object is generated or not. The addresses of each virtual function found in that class are stored in the cells of this table.

Example of Virtual Function in C++

#include<iostream>
using namespace std;

class base {
public:
    void fun_1() { cout << "base-1\n"; }
    virtual void fun_2() { cout << "base-2\n"; }
    virtual void fun_3() { cout << "base-3\n"; }
    virtual void fun_4() { cout << "base-4\n"; }
};

class derived : public base {
public:
    void fun_1() { cout << "derived-1\n"; }
    void fun_2() { cout << "derived-2\n"; }
    void fun_4(int x) { cout << "derived-4\n"; }
};

int main()
{
    base *p;
    derived obj1;
    p = &obj1;

    p->fun_1();

    p->fun_2();

    p->fun_3();

    p->fun_4();


    
    return 0;
}

Output

Explanation of the above code
First, we create a base class so the pointer of the base class is created first, and then we have initialized it and will initialize it with the address of the corresponding derived class. Now, whenever we create an object of the derived class then the class which contains the address of the VTABLE of the derived class will be connected by a pointer that is created by the compiler.

And we have used kind of a similar concept in the above example for fun1() as it is in the base class so the base class is called for the fun2() we have the virtual keyword in the base class so the derived class is called and the function is overridden but for fun3() and fun4() we do not have the virtual keyword hence the function is not overridden and hence the base class is called.

Pure Virtual Function in C++

The virtual function is used as a placeholder and is not used to perform any task. The “do-nothing” function is a function that has no definition. As explained above the do-nothing function are known as pure virtual functions. When we declare a function in the base class with no definition with respect to the base class is known as a pure virtual function.

Abstract base classes are the classes that contain pure virtual functions and they cannot be used to declare objects of their own. There are a few main functions of the base class that is creating some functions and passing those traits to the derived class and we create a pointer pointing to the base class which is used to achieve run time polymorphism.

Example of Pure Virtual Function in C++

Here we will see the example of a pure virtual function in c++.

#include <iostream>  
using namespace std;  
class Base  
{  
    public:  
    virtual void show() = 0;  
};  
class Derived : public Base  
{  
    public:  
    void show()  
    {  
        std::cout << "This class is derived from the base class." << std::endl;  
    }  
};  
int main()  
{  
    Base *bptr;  
    //Base b;  
    Derived d;  
    bptr = &d;  
    bptr->show();  
    return 0;  
}

Output

Code Explanation of pure virtual function in C++
As you can see in the code of the above example of pure virtual function in c++. That is the base class, we have created a pure virtual function and that function is derived in the derived class hence the output is shown as “ This class is derived from the base class”. And this base class is known as the abstract base class.

Limitation of Virtual Function in C++

  • The virtual function is a bit slower compared to other functions as in this we are not calling the function directly we are following the proper mechanism which is making the process a bit slower and cannot be optimized further
  • It is quite difficult to find the error as it is not easy to debug and it is not easy to find the root cause of the error.

FAQs Related to Virtual Function in C++

1. What do you understand by pure virtual function?
When a virtual function does not have any implementation and we have to only declare it is known as a pure virtual function or abstract function.
2. Can we have both the constructor and destructor of virtual function in c++?
No, we cannot have a constructor of a virtual function but we can have a destructor of a virtual function in c++.
3. Can we call a virtual function inside a non-virtual function?
Yes, we can call a virtual function from inside a non-virtual function.

Conclusion
In the article, we have studied virtual functions in c++ with their use, rules, and the example showing the code before the use of virtual function and one with the use of virtual function with proper explanation and followed by pure virtual question with its example and at last the limitation of the virtual function.

Leave a Reply

Your email address will not be published. Required fields are marked *