Table of contents
1.
Introduction
2.
What is Polymorphism?
3.
Types of Polymorphism in C++
3.1.
Compile-Time Polymorphism in C++
3.1.1.
Function Overloading
3.2.
C++
3.2.1.
Operator Overloading
3.3.
C++
3.4.
Run-time Polymorphism in C++
3.4.1.
Function Overriding
3.4.2.
Example of Function Overriding 
3.5.
C++
4.
C++ Runtime Polymorphism Example
4.1.
Example:
4.2.
C++
5.
Runtime Polymorphism with Data Members
5.1.
Example
5.2.
C++
6.
Frequently Asked Questions
6.1.
What is polymorphism vs overriding in C++?
6.2.
Why do we need polymorphism?
6.3.
What is compile-time and runtime polymorphism?
7.
Conclusion
Last Updated: Sep 16, 2024
Easy

Polymorphism in C++

Author Teesha Goyal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Polymorphism in C++ is a core concept of object-oriented programming that allows functions or methods to perform different tasks based on the object type. This flexibility makes code more dynamic and easier to manage. 

Polymorphism in C++

In this article, we explore the types of polymorphism, its implementation, and how it enhances C++ programming.

What is Polymorphism?

Polymorphism is made up of two words; “poly” means many, “morphism” means forms which means having the same name but many different functions simultaneously. It is one of the prominent features of object-oriented programming.

Let’s have a look at a real-life example of polymorphism

Suppose two people have the same name, ' Ram’, but both don't need to have the same behaviour and characteristics except for some. So they may have some common characteristics but also have their own unique personality. This is polymorphism.

Types of Polymorphism in C++

In C++, we have two types of polymorphism. The following chart shows the categorisation of polymorphism in C++.

Compile-Time Polymorphism in C++

A function is called during program compilation in compile-time polymorphism. In this type of polymorphism, the decision of which function to invoke is taken at compile time. This type of polymorphism is known as early binding or static binding. This can be achieved via function overloading and operator overloading.

Function Overloading

The term "function overloading" refers to the ability of a single function to perform multiple tasks. In C++, a single function with the same name and different types of arguments is used to perform multiple tasks. At the time of program compilation, the function overloading function will be called. It exemplifies compile-time polymorphism.

When defining two or more functions in C++ with the same name, the number of parameters or the type of parameters should be different.

Example of Function overloading in C++

  • C++

C++

#include<iostream>
using namespace std;

class Areas{
   public:
   //Function to find area of square
   int area(int side){
       return side*side;
   }

   //Function to find area of rectangle
   int area(int length, int breadth){
       return length*breadth;
   }

   //Function to find area of circle
   float area(float r){
       return 3.14*r*r;
   }
};

//driver function
int main(){

   Areas square;
   //Here, the first area function is called as we have provided only one parameter, and that is also of integer type
   cout<<"The area of a square of side 5 is: "
       <<square.area(5)<<endl;

   Areas rectangle;
   //Here, the second function is called because we have passed two parameters
   cout<<"The area of a rectangle of length 6 and breadth 8 is: "
       <<rectangle.area(6,8)<<endl;

   Areas circle;
   //here we have to define a variable radius as float to tell the compiler to invoke the third area function
   float radius = 7.0;
   cout<<"The area of a circle of side 7 is: "
       <<circle.area(radius)<<endl;

   return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

The area of a square of side 5 is: 25
The area of a rectangle of length 6 and breadth 8 is: 48
The area of a circle of side 7 is: 153.86


You can also compile this code with the help of Online C++ Compiler


Operator Overloading

The term "function overloading" refers to the ability of a single operator to perform multiple tasks. In C++, a single operator with the same name and different types of arguments is used to perform multiple tasks. The advantage of operator overloading is that it allows you to perform multiple operations with the same operator.

Example of Operator overloading in C++

  • C++

C++

#include<iostream>
using namespace std;

class Complex{
   public:
   int real;
   int imaginary;

   //Constructor of complex class
   Complex(int new_real = 0, int new_imaginary = 0){
       real = new_real;
       imaginary = new_imaginary;
   }

   //overloading + operator to add two complex numbers by just using a + operator between two complex objects
   Complex operator + (const Complex& obj) {
       Complex tmp;
       tmp.real = real + obj.real;
       tmp.imaginary = imaginary + obj.imaginary;
       return tmp;
   }

   //To print the number on output
   void print_number(){
       cout<<real<<" + "<<imaginary<<"i"<<endl;
   }
};

//driver function
int main(){

   //Creating two complex class objects C1 and C2
   Complex C1(5,6), C2(2,3);
   cout<<"C1 = ";
   C1.print_number();
   cout<<"C2 = ";
   C2.print_number();

   //adding C1 and C2 and storing the value in C3 using operator overloading
   Complex C3 = C1 + C2;
   cout<<"C3 = C1 + C2 = ";
   C3.print_number();

   //Using same + operator to add two integers
   cout<<"The sum of 10 and 15 is: "<<10+15;

   return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

C1 = 5 + 6i
C2 = 2 + 3i
C3 = C1 + C2 = 7 + 9i
The sum of 10 and 15 is: 25

Run-time Polymorphism in C++

Functions are invoked during program execution in a Runtime polymorphism. The decision is made at run time and not compile time. As a result, it is referred to as late or dynamic binding. Runtime polymorphism includes the ability to override functions. In the case of function overriding, multiple methods with the same name and different types of parameter lists are used.

It's done with the help of virtual functions and pointers. As it is known at run time, it provides slow execution. As a result, it is more adaptable, as everything is done at runtime.

Must Read Dynamic Binding in C++

Function Overriding

We give the new definition to the base class function in the derived class when we use function overriding. The base function has so far been overridden at that point. Only in the 'derived class' could this be possible. We have two definitions of the same function in function overriding: one in the superclass and one in the derived class. At runtime, the decision is made about which function definitions must be called. This is why it is referred to as 'Runtime polymorphism’. It is achieved in C++ using virtual functions.

Virtual Functions

A member function in the base class is a virtual function. A derived class can be used to redefine it. It is a type of polymorphism that occurs during run time. The virtual function must be declared using the virtual keyword in the base class. A virtual function does not have a fixed state.

The virtual function informs the compiler whether the function should be bound dynamically or late. If it is required to use a single pointer to refer to the objects of multiple classes. This is because we will have to devise a pointer to the base class that refers to all derived objects.

The object, however, always executes the base class function when the base class pointer includes the derived class address. We will use the virtual function to solve this problem.

When we announce a virtual function, the compiler decides which one to call at runtime.

Example of Function Overriding 

  • C++

C++

#include<iostream>
using namespace std;

//defining the base class
class Base_class{
   public:
   int base_var = 25;

   //defining display function as virtual to override it in derived class
   virtual void display(){
       cout<<"The value of the base variable is: "<<base_var<<endl;
   }
};

//defining the derived class
class Derived_class: public Base_class{
   public:
   int derived_var = 80;

   //Overriding the display function
   void display(){
       cout<<"The value of the base variable is: "
           <<base_var<<endl
           <<"The value of the derived variable is: "
           <<derived_var<<endl;
   }
};

//driver function
int main(){

   Derived_class obj;
   Base_class* ptr = &obj;
   ptr->display();

   return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

The value of the base variable is: 25
The value of the derived variable is: 80

 

Know What is Object in OOPs here in detail.

C++ Runtime Polymorphism Example

Runtime polymorphism in C++ occurs when a function is overridden in a derived class and called through a pointer or reference of the base class. This type of polymorphism is achieved using virtual functions. It allows a program to determine at runtime which function should be invoked, based on the type of the object that is being referred to.

Example:

  • C++

C++

#include <iostream>
using namespace std;

class Base {
public:
virtual void display() {
cout << "Display of Base class" << endl;
}
};

class Derived : public Base {
public:
void display() override {
cout << "Display of Derived class" << endl;
}
};

int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;

// Runtime polymorphism
basePtr->display(); // Output: Display of Derived class

return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Display of Derived class


In this example, the display() function is declared as virtual in the base class. The base class pointer basePtr points to the derived class object. When display() is called using the base class pointer, the derived class version of display() is executed at runtime.

Runtime Polymorphism with Data Members

Runtime polymorphism in C++ is not supported for data members. This is because data members are not accessed through virtual functions, and C++ does not allow overriding data members in derived classes. Even if a derived class defines a data member with the same name as that in the base class, the data member is not treated polymorphically. The type of the pointer or reference determines which version of the data member is accessed.

Example

  • C++

C++

#include <iostream>
using namespace std;

class Base {
public:
int value = 10;
};

class Derived : public Base {
public:
int value = 20;
};

int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;

// Accessing data member through base class pointer
cout << "Base value: " << basePtr->value << endl; // Output: Base value: 10
cout << "Derived value: " << derivedObj.value << endl; // Output: Derived value: 20

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output

Base value: 10
Derived value: 20

 


In this example, both Base and Derived classes have a data member value. Even though basePtr points to a Derived class object, the value accessed through the base class pointer is the Base class's value (10). The data member in C++ is not resolved polymorphically, unlike member functions.

Frequently Asked Questions

What is polymorphism vs overriding in C++?

Polymorphism allows the same function to behave differently in different contexts. Function overriding is a type of polymorphism where a derived class provides its specific implementation of a virtual function from the base class.

Why do we need polymorphism?

Polymorphism allows flexibility in programming by enabling a single interface to represent different types of objects. It enhances code reusability and simplifies maintenance, making programs more scalable and adaptable to changes.

What is compile-time and runtime polymorphism?

Compile-time polymorphism occurs during compilation, achieved using function overloading or operator overloading. Runtime polymorphism happens at runtime, typically using virtual functions, enabling behavior to be determined based on the object type at execution.

Conclusion

In this article, We discussed Polymorphism in C++. We learned the two types of polymorphism Compile-Time and Run-Time polymorphism. We also discussed the ways to achieve polymorphism in C++.

Recommended Reading:

Four Pillars of OOPS

Are you planning to ace the interviews of reputed product-based companies like Amazon, Google, Microsoft, and more? 

Check out this article - Compile Time Polymorphism

Live masterclass