Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Virtual Function in C++

Last Updated on May 18, 2023 by Prepbytes

In object-oriented programming, a virtual function is a crucial concept that allows a derived class to provide its implementation of a method already defined in the base class. The virtual keyword is used to declare a function as virtual in the base class, indicating that it can be overridden by derived classes.

The use of virtual functions enables polymorphism, which means that a single interface can be utilized to represent various objects of different classes. This allows for more flexible and extensible code, as the behavior of a function can vary based on the actual type of the object being referenced.

What is a Virtual Function in C++?

In C++, a virtual function is a member function of a class that can be overridden by derived classes. It enables polymorphism, allowing different objects of related classes to be accessed through a common interface.

To declare a virtual function, the virtual keyword is used in the base class. Derived classes can then provide their own implementation of the virtual function by overriding it using the same signature.

When a virtual function is called using a base class pointer or reference, the actual implementation to execute is determined at runtime based on the dynamic type of the object. This is known as dynamic or late binding.

Virtual functions provide a mechanism for achieving runtime polymorphism, as the appropriate function implementation is selected based on the object’s type rather than the static type of the pointer or reference.

It’s important to note that only member functions can be declared as virtual, not static or friend functions. Additionally, a virtual function in the base class can be optionally overridden by derived classes, but it’s not mandatory.

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.

Conclusion
In conclusion, virtual functions in C++ play a fundamental role in achieving polymorphism and providing a common interface for related classes. They allow derived classes to override the implementation of a function defined in the base class, enabling dynamic binding and runtime polymorphism. By using virtual functions, C++ provides a powerful mechanism for code reusability, flexibility, and extensibility in object-oriented programming.

FAQs Related to Virtual Function in C++

Q1. What do you understand by pure virtual function?
Ans. 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.

Q2. Can we have both the constructor and destructor of virtual function in c++?
Ans. No, we cannot have a constructor of a virtual function but we can have a destructor of a virtual function in c++.

Q3. Can we call a virtual function inside a non-virtual function?
Ans. Yes, we can call a virtual function from inside a non-virtual function.

Q4. Can a virtual function be private in C++?
Ans. Yes, a virtual function can be declared as private in a class in C++. However, it can still be overridden by derived classes that have access to the base class’s private members. This allows for the implementation of polymorphism while maintaining encapsulation.

Q5. Can a constructor or destructor be virtual in C++?
Ans. Yes, a constructor or destructor can be virtual in C++. However, it is less common to declare them as virtual. The virtual keyword is typically used for member functions that are intended to be overridden and provide polymorphic behavior.

Leave a Reply

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