Categories: C++

Virtual Functions in C++

A virtual function is a member function declared in a base class that is re-defined (overridden) by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and execute the derived class’s version of the function.

Example:

Here we are not using any virtual functions.

#include <iostream>  
using namespace std;  
class A  
{  
   int x=13;  
    public:  
     void display()  
    {  
        std::cout << "Value of x is : " << x<<std::endl;  
    }  
};  
class B: public A  
{  
    int y = 90;  
    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:
Value of x is : 13

*a is the base class pointer in the preceding example. The pointer can only access base class members and not derived class members. Although C++ allows the base pointer to point to any object derived from the base class, it cannot access the derived class’s members directly. As a result, a virtual function is required to allow the base pointer to access the members of the derived class.

Now let us see the same example but with the use of the virtual function.

#include <iostream>  
using namespace std;  
class A  
{  
   int x=13;  
    public:  
    virtual void display()  
    {  
        std::cout << "Value of x is : " << x<<std::endl;  
    }  
};  
class B: public A  
{  
    int y = 90;  
    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:
Value of y is : 90

Note: Using the virtual keyword, we can call the private function of a derived class from the base class pointer. Only at compile time does the compiler look for access specifiers. As a result, when late binding occurs at run time, it does not check whether we are calling a private or public function.

Operation of virtual functions (concept of VTABLE and VPTR):

As we know if a class contains a virtual function, the compiler performs two actions.

  • If an object of that class is created, a virtual pointer (VPTR) is added as a data member of the class to point to the class’s VTABLE. A new virtual pointer is inserted as a data member of that class for each new object created.
  • Whether an object is created, the class contains a static array of function pointers called VTABLE as a member. The address of each virtual function in that class is stored in the cells of this table.

Note: also read about Order of Constructor Call in C++

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 month ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

2 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

2 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

3 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 months ago