Polymorphism in C++: Types of Polymorphism

Polymorphism in C++: Types of Polymorphism

21 May 2024
Advanced
7.4K Views
17 min read
Learn with an interactive course and practical hands-on labs

Free C++ Foundation Course: Learn C++ In 21 Days

Polymorphism in C++: An Overview

Polymorphism in C++ is using the same functions or operators multiple times in multiple ways. In this C++ tutorial, we'll dive into this important OOPs concept in C++. It plays an important role in increasing your code reusability. Therefore, let us now discuss it in detail. For more information and hands-on consider our C++ Certification program and get a chance to become a certified C++ developer.

What is Polymorphism in C++?

Polymorphism is made up of two words, poly means more than one and morphs means forms. Therefore, polymorphism means the ability to take more than one form. This property makes the same entities such as functions, and operators perform differently in different scenarios. You can perform the same task in different ways. This makes polymorphism in C++ an important OOP concept.

Real-Life Example of Polymorphism

In the given figure, a person when a student pays his bills. After completing his studies, the same person becomes a millionaire and pays bills of various types. Here the person is the same and the function he performs is also the same. The only difference is in the type of bills.

Real Life Example of Polymorphism

Types of Polymorphism in C++

There are two types of polymorphism in the C++ programming language. These are:

  1. Compile time Polymorphism
  2. Runtime Polymorphism

Types of Polymorphism in C++

  1. Compile time Polymorphism in C++

In this, the compiler at the compilation stage knows which functions to execute during the program execution. It matches the overloaded functions or operators with the number and type of parameters at the compile time.

The compiler performs compile-time polymorphism in C++ in two ways:

  • Function Overloading
  • Operator Overloading

Read More - C++ Interview Interview Questions for Experienced

  • Function Overloading in C++

We already saw how to use the same function with different numbers and types of parameters for different tasks in the section, C++Function Overloading.

You are also aware of inheritance in C++ very well. Therefore, we will now implement the concept of function overloading with parent and derived classes in C++.

Example of Function Overloading in C++ Compiler


#include <iostream>
using namespace std;

class DotNetTricks {
public:
 void print(int x) {
 cout << "DotNetTricks was established in " << x << endl;
 }
};

class ScholarHat : public DotNetTricks {
public:
 void print(string message) {
 cout << "ScholarHat was founded by the DotNetTricks founder, " << message << endl;
 }
};

int main() {
 DotNetTricks obj1;
 ScholarHat obj2;

 obj1.print(2015);
 obj2.print("Shailendra Chauhan"); // Calls the overloaded print(string) in Derived class
 return 0;
}
  • The print() function with different parameter types is declared in both the classes, DotNetTricks and ScholarHat.
  • The object obj1 of the parent class, DotNetTricks calls the print() function of the parent class with an int argument.
  • The object obj2 of the child class, ScholarHat calls the overloaded print() function in the derived class with a string argument.
  • Hence, we can say that the child class, ScholarHat has overloaded the print() function of the parent class, DotNetTricks.

Output

DotNetTricks was established in 2015
ScholarHat was founded by the DotNetTricks founder, Shailendra Chauhan

  • Operator Overloading in C++

Operator overloading in C++ is basically function overloading, where different operator functions have the same symbol but different operands. And, depending on the operands, different operator functions are executed. The operands here are the user-defined data types like objects or structures and not the basic data types.

Example of Operator Overloading in C++


#include <iostream>
#include <string>
using namespace std;
// Class to implement operator overloading for concatenating the strings
class MyString {

public:
 char s1[25], s2[25];

 // Parameterized Constructor
 MyString(char str1[], char str2[])
 {
 // Initialize the string to class object
 strcpy(this->s1, str1);
 strcpy(this->s2, str2);
 }

 // + Overload Operator to concatenate the string
 void operator+()
 {
 cout << "\nConcatenation: " << strcat(s1, s2);
 }
};

int main()
{
 char str1[] = "Welcome to";
 char str2[] = "ScholarHat";

 // Declaring and initializing the class with the above two strings
 MyString overload(str1, str2); 

 // Call operator function
 +overload;
 return 0;
}
  • In the above code, we have overloaded the + operator in the MyString class, allowing you to concatenate two MyString objects.
  • We have concatenated str1 and str2 objects using the + operator, and the result is stored in the result variable.

Output

Welcome to ScholarHat

  1. Runtime Polymorphism in C++

In this, the compiler at the compilation stage does not know the functions to execute during the program execution. The function call is not resolved during compilation, but it is resolved in the run time based on the object type. It means the function is invoked by seeing which object is calling it; the parent class object or the derived class object. This is also known as dynamic binding or late binding.

Runtime Polymorphism in C++ is achieved in two ways:

  • Function Overriding
  • Virtual Functions

  • Function Overriding in C++

In this, the method with the same name, type, and number of parameters is defined in both the base and derived classes. When the object of the derived class calls this method, the method in the derived class gets executed instead of the base class. Therefore, we can say that the method of the derived class has overridden the method of the base class.

Example of Function Overriding in C++


#include <iostream>
using namespace std;

class DotNetTricks {
public:
 void print() {
 cout << "Welcome to DotNetTricks" << endl;
 }
};

class ScholarHat : public DotNetTricks {
public:
 void print() {
 cout << "Welcome to ScholarHat" << endl;
 }
};

int main() {
 ScholarHat obj1;

 // Call the print() function of the ScholarHat class
 obj1.print();

 return 0;
}

In the above code, the base class Scholarhat overrides the print() function of the parent class, DotNetTricks. When you create an object of ScholarHat and call its print() function, it executes the version of the function defined in the ScholarHat class.

Output

Welcome to ScholarHat

We can even access the overridden function of the base class using the scope resolution operator :: and the pointer of the base class. We will see this in the next section, C++ Function Overriding.

  • Virtual Function in C++

When we use the pointer of the base class to override the function of the base class in the derived class, it is not done. Therefore virtual functions in C++ come into play. If you declare a method in the base class as virtual and use a pointer of the base class to call that method, it calls the method of the derived class and not the base class. Thus, the virtual function in the base class helps the derived class method to override that function.

Example of Virtual Function in C++


#include <iostream>
using namespace std;

class DotNetTricks {
public:
 virtual void print() {
 cout << "Welcome to DotNetTricks" << endl;
 }
};

class ScholarHat : public DotNetTricks {
public:
 void print() {
 cout << "Welcome to ScholarHat" << endl;
 }
};

int main() {
 ScholarHat sobj1;

 // Pointer of the Base type that points to sobj1
 DotNetTricks* ptr = &sobj1;

 // Calls the member function of the Derived class
 ptr->print();

 return 0;
}

The above C++ code in C++ Editor creates an object of ScholarHat and uses a pointer of the base class type (DotNetTricks) to demonstrate function overriding. When ptr->print()is called, it will invoke the print() function of the ScholarHat class due to the virtual print() function in the DotNetTricks class.

Output

Welcome to ScholarHat

Read more about virtual functions in our C++ Virtual Functions tutorial

Difference between Runtime and Compile time polymorphism

Compile-time polymorphismRuntime polymorphism
the function to be invoked is known at the compile timethe function to be invoked is known at the run time
It is also known as static binding, overloading, or early binding.It is also known as late binding, overriding, or Dynamic binding.
Overloading is a compile-time polymorphism where more than one method has the same name but with a different number of parameters or the type of the parameters.Overriding is a run-time polymorphism where more than one method has the same name, number of parameters, and type of parameters.
This particular polymorphism is achieved by operator overloading and function overloading.This particular polymorphism is achieved using pointers and virtual functions.
It is faster as the function to be invoked is known at the compile timeIt is slower as the function to be invoked is known at the run time
It is less flexible because all the execution is done at the compile time.It is more flexible because all the execution is done at the run time.
Summary

So here we have covered an important OOPs concept in C++, polymorphismand its types. If you thoroughly get through the article, you will definitely understand it. It is quite confusing and difficult to understand but if you are following the sequence from OOPs concepts in C++, you won't find it that difficult. For further learning consider our C++ Certification.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this