The Wayback Machine - https://web.archive.org/web/20240917200110/https://www.geeksforgeeks.org/virtual-functions-and-runtime-polymorphism-in-cpp/
Open In App

Virtual Functions and Runtime Polymorphism in C++

Last Updated : 09 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphism.

The term Polymorphism means the ability to take many forms. It occurs if there is a hierarchy of classes that are all related to each other by inheritance. In simple words, when we break down Polymorphism into ‘Poly – Many’ and ‘morphism – Forms’ it means showing different characteristics in different situations. 

Polymorphism

Class Hierarchy

Note: In C++ what calling a virtual functions means is that; if we call a member function then it could cause a different function to be executed instead depending on what type of object invoked it. 
Because overriding from derived classes hasn’t happened yet, the virtual call mechanism is disallowed in constructors. Also to mention that objects are built from the ground up or follows a bottom to top approach.

 

Consider the following simple program as an example of runtime polymorphism. The main thing to note about the program is that the derived class’s function is called using a base class pointer.
The idea is that virtual functions are called according to the type of the object instance pointed to or referenced, not according to the type of the pointer or reference.
In other words, virtual functions are resolved late, at runtime.

Now, we’ll look at an example without using the concepts of virtual function to clarify your understanding.

C++




// C++ program to demonstrate how we will calculate
// area of shapes without virtual function
#include <iostream>
using namespace std;
 
// Base class
class Shape {
public:
    // parameterized constructor
    Shape(int l, int w)
    {
        length = l;
        width = w;
    }
    int get_Area()
    {
        cout << "This is call to parent class area\n";
        // Returning 1 in user-defined function means true
        return 1;
    }
 
protected:
    int length, width;
};
 
// Derived class
class Square : public Shape {
public:
    Square(int l = 0, int w = 0)
        : Shape(l, w)
    {
    } // declaring and initializing derived class
    // constructor
    int get_Area()
    {
        cout << "Square area: " << length * width << '\n';
        return (length * width);
    }
};
// Derived class
class Rectangle : public Shape {
public:
    Rectangle(int l = 0, int w = 0)
        : Shape(l, w)
    {
    } // declaring and initializing derived class
    // constructor
    int get_Area()
    {
        cout << "Rectangle area: " << length * width
             << '\n';
        return (length * width);
    }
};
 
int main()
{
    Shape* s;
 
    // Making object of child class Square
    Square sq(5, 5);
 
    // Making object of child class Rectangle
    Rectangle rec(4, 5);
    s = &sq; // reference variable
    s->get_Area();
    s = &rec; // reference variable
    s->get_Area();
 
    return 0; // too tell the program executed
    // successfully
}


Output

This is call to parent class area
This is call to parent class area

In the above example:

  • We store the address of each child’s class Rectangle and Square object in s and
  • Then we call the get_Area() function on it,
  • Ideally, it should have called the respective get_Area() functions of the child classes but
  • Instead, it calls the get_Area() defined in the base class.
  • This happens due to static linkage which means the call to get_Area() is getting set only once by the compiler which is in the base class.

Example: C++ Program to Calculate the Area of Shapes using Virtual Function

C++




// C++ program to demonstrate how we will calculate
// the area of shapes USING VIRTUAL FUNCTION
#include <fstream>
#include <iostream>
using namespace std;
 
// Declaration of Base class
class Shape {
public:
    // Usage of virtual constructor
    virtual void calculate()
    {
        cout << "Area of your Shape ";
    }
    // usage of virtual Destuctor to avoid memory leak
    virtual ~Shape()
    {
        cout << "Shape Destuctor Call\n";
    }
};
 
// Declaration of Derived class
class Rectangle : public Shape {
public:
    int width, height, area;
 
    void calculate()
    {
        cout << "Enter Width of Rectangle: ";
        cin >> width;
 
        cout << "Enter Height of Rectangle: ";
        cin >> height;
 
        area = height * width;
        cout << "Area of Rectangle: " << area << "\n";
    }
 
    // Virtual Destuctor for every Derived class
    virtual ~Rectangle()
    {
        cout << "Rectangle Destuctor Call\n";
    }
};
 
// Declaration of 2nd derived class
class Square : public Shape {
public:
    int side, area;
 
    void calculate()
    {
        cout << "Enter one side your of Square: ";
        cin >> side;
 
        area = side * side;
        cout << "Area of Square: " << area << "\n";
    }
   
   // Virtual Destuctor for every Derived class
    virtual ~Square()
    {
        cout << "Square Destuctor Call\n";
    }
};
 
int main()
{
 
    // base class pointer
    Shape* S;
    Rectangle r;
 
    // initialization of reference variable
    S = &r;
 
    // calling of Rectangle function
    S->calculate();
    Square sq;
 
    // initialization of reference variable
    S = &sq;
 
    // calling of Square function
    S->calculate();
 
    // return 0 to tell the program executed
    // successfully
    return 0;
}


Output:

Enter Width of Rectangle: 10
Enter Height of Rectangle: 20
Area of Rectangle: 200
Enter one side your of Square: 16
Area of Square: 256

What is the use? 
Virtual functions allow us to create a list of base class pointers and call methods of any of the derived classes without even knowing the kind of derived class object. 

Real-Life Example to Understand the Implementation of Virtual Function

Consider employee management software for an organization.
Let the code has a simple base class Employee, the class contains virtual functions like raiseSalary(), transfer(), promote(), etc. Different types of employees like Managers, Engineers, etc., may have their own implementations of the virtual functions present in base class Employee. 

In our complete software, we just need to pass a list of employees everywhere and call appropriate functions without even knowing the type of employee. For example, we can easily raise the salary of all employees by iterating through the list of employees. Every type of employee may have its own logic in its class, but we don’t need to worry about them because if raiseSalary() is present for a specific employee type, only that function would be called.

CPP




// C++ program to demonstrate how a virtual function
// is used in a real life scenario
 
class Employee {
public:
    virtual void raiseSalary()
    {
        // common raise salary code
    }
 
    virtual void promote()
    {
        // common promote code
    }
};
 
class Manager : public Employee {
    virtual void raiseSalary()
    {
        // Manager specific raise salary code, may contain
        // increment of manager specific incentives
    }
 
    virtual void promote()
    {
        // Manager specific promote
    }
};
 
// Similarly, there may be other types of employees
 
// We need a very simple function
// to increment the salary of all employees
// Note that emp[] is an array of pointers
// and actual pointed objects can
// be any type of employees.
// This function should ideally
// be in a class like Organization,
// we have made it global to keep things simple
void globalRaiseSalary(Employee* emp[], int n)
{
    for (int i = 0; i < n; i++) {
        // Polymorphic Call: Calls raiseSalary()
        // according to the actual object, not
        // according to the type of pointer
        emp[i]->raiseSalary();
    }
}


Like the ‘globalRaiseSalary()‘ function, there can be many other operations that can be performed on a list of employees without even knowing the type of the object instance. 
Virtual functions are so useful that later languages like Java keep all methods virtual by default.

How does the compiler perform runtime resolution?

The compiler maintains two things to serve this purpose:

  • vtable: A table of function pointers, maintained per class. 
  • vptr: A pointer to vtable, maintained per object instance (see this for an example).
     

compiler perform runtime resolution

The compiler adds additional code at two places to maintain and use vptr.

1. Code in every constructor. This code sets the vptr of the object being created. This code sets vptr to point to the vtable of the class. 

2. Code with polymorphic function call (e.g. bp->show() in above code). Wherever a polymorphic call is made, the compiler inserts code to first look for vptr using a base class pointer or reference (In the above example, since the pointed or referred object is of a derived type, vptr of a derived class is accessed). Once vptr is fetched, vtable of derived class can be accessed. Using vtable, the address of the derived class function show() is accessed and called.

Is this a standard way for implementation of run-time polymorphism in C++? 
The C++ standards do not mandate exactly how runtime polymorphism must be implemented, but compilers generally use minor variations on the same basic model.



Previous Article
Next Article

Similar Reads

Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &amp;lt;iostream&amp;gt; using namespace std; class Base { public: void print() { cout &amp;lt;&amp;lt; &amp;quot;Base class print function \n&amp;quot;; } void invoke() { cout &amp;lt;&amp;lt; &amp;quot;Base class invoke function \n&amp;quot;;
2 min read
Difference Between Compile Time And Run Time Polymorphism In C++
In this article, we will discuss the differences between the compile-time and runtime polymorphism in C++. What is Polymorphism? Poly means many and morph means forms or shape. Thus the word Polymorphism comes from Greek and it basically means having many forms. For example, Your DAD is your father. He's your mom's Husband. He's your grandma's son
4 min read
Difference between Inheritance and Polymorphism
Inheritance is one in which a new class is created that inherits the properties of the already exist class. It supports the concept of code reusability and reduces the length of the code in object-oriented programming. Types of Inheritance are:Single inheritanceMulti-level inheritanceMultiple inheritancesHybrid inheritanceHierarchical inheritanceEx
5 min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is 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 have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Can Virtual Functions be Inlined in C++?
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. Inline functions are used to replace the function calling location with the definition of the inline function at compil
2 min read
Can Virtual Functions be Private in C++?
A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class. Example 1: Calling Private Virtual Function from Base Class Pointer to Derived Class Instance [GFGTABS] C++ // C++ progr
4 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Default Arguments and Virtual Function in C++
Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr
3 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Difference Between Friend Function and Virtual Function in C++
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and
3 min read
How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints "Base::show() called".
3 min read
C++ interview questions on virtual function and abstract class
1. What is a pure virtual function ? Ans. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example. [GFGTABS] CPP // An abstract class class Test { // Data members of class publi
4 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Target Corporation Interview Experience | On-Campus Virtual Hiring
Round 1 - Online test This round has MCQ s regrading English reading comprehension, Reasoning, logical, Quantitative(Numerical) and technical questions. Technical questions were related to computer science domain. This round also has 2 coding questions: Counting the duplicate elements in an arrayOptimal oil flow problem Both questions had 2 public
3 min read
ARM Interview Experience for Intern (On-Campus Virtual 2020)
ARM talent acquisition team visited our campus virtually for an intern role in the verification domain. There were totally 3 rounds, Round 1 (Written Test) : 30 Aptitude (Time &amp; Work, Time and Distance, percentages, profit and loss, SI &amp; CI covered all major topics in aptitude)70 Technical (Digital, C basics &amp; Guessing the output, OS co
2 min read
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // CPP program without virtual destructor // causing u
2 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
Pure Virtual Destructor in C++
A pure virtual destructor can be declared in C++. After a destructor has been created as a pure virtual object(instance of a class), where the destructor body is provided. This is due to the fact that destructors will not be overridden in derived classes, but will instead be called in reverse order. As a result, for a pure virtual destructor, you m
4 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
Virtual destruction using shared_ptr in C++
Prerequisite: shared_ptr, Virtual Destructor As we know, deleting a derived class object using a pointer to a base class that has non-virtual destructor results in undefined behavior. Thus, we make the base class destructor virtual so that the polymorphic objects are being deleted properly in the correct order (i.e. the reverse order of their creat
3 min read
Virtual base class in C++
Virtual base classes are used in virtual inheritance in a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritances.  Need for Virtual Base Classes: Consider the situation where we have one class A . This class A is inherited by two other classes B and C. Both these class are inhe
3 min read
Advanced C++ | Virtual Constructor
In C++, we CANNOT make a constructor virtual. The reason is that C++ is a statically typed language, so the concept of a virtual constructor is a contradiction because the compiler needs to know the exact type at compile time to allocate the correct amount of memory and initialize the object correctly. If we attempt to make a constructor virtual, t
8 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
asin() and atan() functions in C/C++ with Example
In C++, asin() and atan() is a predefined function used for mathematical calculations. math.h is the header file required for various mathematical functions. All the functions available in this library take double as an argument and return double as the result. asin() Method asin() function is used to find the arc sine of a number means give a sin
3 min read
Explicitly Defaulted and Deleted Functions in C++ 11
Defaulted Function What is a Defaulted Function? Explicitly defaulted function declaration is a new form of function declaration that is introduced into the C++11 standard which allows you to append the '=default;' specifier to the end of a function declaration to declare that function as an explicitly defaulted function. This makes the compiler ge
5 min read
Practice Tags :