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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago