Understanding Polymorphism in C++: Types of Polymorphism

Shailendra Chauhan  12 min read
12 Sep 2023
Intermediate
942 Views

Polymorphism in C++: An Overview

Have you ever had the feeling that something was just too complicated and your mind kept wrapping itself around ideas without actually putting them into practice? Well, if you're familiar with writing code in C++, then this is probably a very familiar feeling for you. And don't worry, because today we're going to learn about one of the core principles of programming in C++ programming language, which is polymorphism. So strap on your thinking caps and join us on this journey as we explore all of the amazing things that polymorphism has to offer in C++Online Training and just how it makes life easier for C++ developers!

What is Polymorphism in C++?

Polymorphism in C++ language is a powerful programming technique that allows multiple characteristics of an object to be represented using the same interface. This polymorphic ability allows C++ developers to create code that is more flexible, modular, and easier to maintain. In C++, polymorphism makes it possible for many objects to work together without difficulty, increasing code reuse and making it easier to add new behaviors without changing current classes..

Read more: OOPs concept and object class in C++

Real Life example of Polymorphism in C++ language

Let's understand a real life example of Polymorphism. A lady who behaves like a teacher in a classroom, a mother with her children, or a wife in a home. So a single person has various roles in her life according to the situation.

Polymorphism

Types of Polymorphism in C++

There are two types of Polymorphism in C++ programming language. Those are

  1. Compile time Polymorphism
  2. Runtime Polymorphism

Types of Polymorphism

Compile time Polymorphism

In compile time polymorphism the overloaded functions are invoked by matching the number and type of the arguments. This particular information is available at the time of compilation. It is achievable by doing function overloading and operator overloading which is known as early binding or static binding.

Function Overloading

  • Using the same function name with different parameters is known as function overloading.
  • It can be done by changing the quantity or kinds of arguments.
  • By using the same function name with different parameters, activities can be completed more quickly in object-oriented programming.
  • When overloading functions, it's important to follow certain guidelines.

Example

#include <iostream>
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
int main() {
Calculator calc; 
int sum1 = calc.add(5, 3);
double sum2 = calc.add(4.5, 2.3); 
std::cout << "Sum of integers: " << sum1 << std::endl;
std::cout << "Sum of doubles: " << sum2 << std::endl; 
return 0;
}

The Calculator class in this illustration includes two add functions with the same name but various parameter types (one accepts integers, the other accepts doubles). Function overloading (compile-time polymorphism) is used to call the appropriate add function based on the arguments given during the function call.

Output

Sum of integers: 8
Sum of doubles: 6.8

Operator Overloading

  • You can provide operators in C++ with distinct semantics for particular data types by using operator overloading.
  • For instance, you can concatenate strings by using the addition operator (+), which adds integers but concatenates strings dependent on the type of the operand.

Example

#include <iostream>
#include <string>
class MyString {
private:
std::string str;
public:
MyString() : str("") {} MyString operator+(const MyString& other) {
MyString result;
result.str = this->str + other.str;
return result;
}
void display() {
std::cout << str << std::endl;
}
};
int main() {
MyString str1;
MyString str2;
str1 = "Hello, ";
str2 = "World!";
MyString result = str1 + str2;
result.display();
return 0;
}

In this example, the MyString class's overloaded + operator enables you to concatenate two MyString objects as if they were standard strings. The output is printed using the display method.

Output

Hello, World!

Runtime Polymorphism

Runtime Polymorphism in C++ programming language can be achieved when the method of the object is invoked at the runtime instead of compile time. This process can be achieved by function overriding & virtual functions.

Function Overriding

  • When a derived class gives its own definition for a member function that was first defined in the base class, this is known as function overriding.
  • The implementation from the derived class then takes the place of the overridden base function.

Example

#include <iostream>
class Animal {
public:
void speak() {
std::cout << "Animal makes a sound" << std::endl;
}
};
class Dog : public Animal {
public:
void speak() {
std::cout << "Dog barks" << std::endl;
}
};
class Cat : public Animal {
public:
void speak() {
std::cout << "Cat meows" << std::endl;
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->speak(); // Calls Animal's speak()
animal2->speak(); // Calls Animal's speak()
delete animal1;
delete animal2;
return 0;
}

In this example, the base class Animal has an actual speak() function. Instead of replacing the base class function, the derived classes Dog and Cat conceal it. As a result, using speak() through a reference to the base class calls the function of the base class rather than the functions of the derived class.

Output

Animal makes a sound 
Animal makes a sound

Virtual Function

  • A virtual function is defined (overridden) in the derived class and is declared with the term "virtual" in the base class.
  • Dynamic binding is possible with virtual functions.
  • They must be overridden in the derived class since they are declared in the base class.
  • Polymorphism is made possible by the resolution and calling of virtual functions at runtime.

Example

#include <iostream>
class Animal {
public:
virtual void speak() {
std::cout << "Animal makes a sound" << std::endl;
}
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Dog barks" << std::endl;
}
};
class Cat : public Animal {
public:
void speak() override {
std::cout << "Cat meows" << std::endl;
}
};
int main() {
Animal* animal1 = new Dog();
Animal* animal2 = new Cat();
animal1->speak(); // Calls Dog's speak()
animal2->speak(); // Calls Cat's speak()
delete animal1;
delete animal2;
return 0;
}

In this example, the basic class Animal has a virtual function called speak(). With their own implementations, the derived classes Dog and Cat override this function. Runtime polymorphism is demonstrated when we construct instances of these classes and call the speak() function using pointers to the base class by invoking the appropriate override function based on the actual object type.

Output

Dog barks
Cat meows

Difference between runtime and compile time polymorphism

Compile-time polymorphismRuntime polymorphism
In the compile-time polymorphism, the function which is going to be invoked is known by the developersIn the run time polymorphism, the function which is going to be invoked is known at the run time
It is also known as static binding, overloading, and early binding.It is also known as late binding overriding and 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 different types of 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 by pointers and virtual functions.
Compile time polymorphism in C++ programming language provides fast execution.Run time polymorphism in C++ programming language provides slow execution.
It is less flexible because mainly all the execution is done at the compile time.It is more flexible because all the execution is done at the run time

FAQs

1. What is Polymorphism?

The OOP concept of polymorphism enables objects of several classes to be considered as belonging to a single base class.

2. What are the two 2 types of Polymorphism?

Method overloading (compile-time) & method overriding (run-time) are the two types of polymorphism.

3. What is the difference between Overriding and Overloading?

Overloading entails declaring many methods with the same name in the same class, each with a different set of parameters, as opposed to overriding, which occurs when a subclass offers a specific implementation for a method inherited from a superclass.

4. What is Static Overloading and Dynamic Overloading in Polymorphism?

The terms "static overloading" & "dynamic overloading" are not commonly used when discussing polymorphism; instead, compile-time (static) and run-time (dynamic) polymorphism should be used instead, as was previously mentioned.

Summary

Polymorphism is a powerful tool that can be used in many different ways. When used correctly, it can make your code more concise and easier to read. It can also make your code more flexible and extensible. This article gave you a vast idea about various types of polymorphism in the C++ programming language including the difference between them. As you learn more about C++ in C++ Certification, experiment with polymorphism and see how it can help you write better code.

Share
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at 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 8th time in a row (2016-2023). 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