What does polymorphism mean in C++? Have you ever wondered how the same function or operator can do different things in C++? Like how the + symbol can add numbers and join strings? How does overloading and overriding work? This is possible because of a powerful concept in C++ known as polymorphism. So, what exactly is polymorphism? Why do we use it? How does it help make our code cleaner, reusable, and easier to manage?
In this article, we will understand polymorphism in C++ in detail.
Table of Contents:
What is Polymorphism in C++?
Polymorphism in C++ means ‘many forms’, i.e., using the same function or operator name to perform different tasks depending on context. For example, you can think of an addition operator that behaves differently for an integer and a string in C++.
Polymorphism in C++:
- Reuse code instead of writing it again and again.
- Write cleaner code that is easy to understand.
- Make changes easily in big programs.
- Use one function name for different purposes.
For example, in a smartphone, the camera button takes a photo, and the same button starts video recording if you hold it longer. The same button gives different results.
Types of polymorphism in C++
There are mainly two categories of polymorphism in C++. These are as follows:
1. Compile-time Polymorphism
Compile-time polymorphism in C++ means that the function or operator can be executed at the time of compilation, i.e., before the program runs. It is also called static polymorphism or early binding because the behaviour of the function or the operator is decided by the compiler at compile time.
Compile-time Polymorphism is mainly useful as:
- You can use the same function name for different tasks.
- It makes your code cleaner and easier to read.
- It avoids writing duplicate functions with different names.
You can achieve compile-time polymorphism in C++ in mainly two ways. These are:
A. Function Overloading
Function Overloading is a concept in object-oriented programming in which you can create more than one function with the same name, that act differently with different parameters. In this, the compiler decides which function to call based on the arguments you pass.
Rules of Function Overloading:
- The function should have the same name.
- They must differ in type or number of arguments.
- The return type of the function can be different, but only changing the return type of a function is not enough to make it different from another function. You also have to change the number or the type of parameter to overload it.
Example:
Output:
Explanation: In the above C++ code, there are 3 functions named print, having different parameters, i.e., int, double, and string.
B. Operator Overloading
Operator Overloading in C++ means giving special meaning to different operators like +, -, *, etc., so that they can work with user-defined objects. By default, C++ operators only work with built-in types like int, float. But with operator overloading, we can make them work with our own types.
Operator Overloading in C++
- Makes your code easier to read and understand.
- You can write code using operators instead of using functions like obj1 + obj2, which makes the code more intuitive and readable.
Example:
Output:
Explanation: In the above C++ code, the addition operator is used for adding two numbers, a and b, and two strings, firstName and lastName. The addition operator behaves differently for both integer and string, which shows polymorphism in C++.
Get 100% Hike!
Master Most in Demand Skills Now!
2. Runtime Polymorphism or Dynamic Polymorphism
Runtime polymorphism is a core concept of object-oriented programming. It allows functions with the same name to behave differently based on the object’s type at runtime. It is also called late binding and dynamic polymorphism.
The compiler decides which function to call during the execution of the program at runtime, not during compilation.
To achieve runtime polymorphism, C++ uses:
- Inheritance: A derived class inherits from a base class, meaning it gets all its methods and properties.
- Virtual Functions: A function in the base class is marked with the virtual keyword. This tells the compiler not to bind this function right now, until runtime.
- Function Overriding: The derived class redefines the base class’s virtual function to provide specific behaviour.
- Base Class Pointer or Reference: The base class pointer/reference can hold an object of the derived class, allowing dynamic decision-making.
You can achieve runtime polymorphism in C++ in mainly two ways. These are:
A. Virtual Function
A virtual function is a function that is declared in a base class and is overridden in its derived class. At runtime, the version of the function that is called by the user depends on the actual type of the object, not its pointer or reference, which helps you to achieve runtime polymorphism. It is declared using the virtual keyword in the base class.
For example, a remote has a power button, and it will turn on the television, when connected to the TV. Similarly, it turns on the fan when connected to the fan. This means that the remote only performs its function, and it does not give importance to what it controls, i.e., the fan or television. It is similar to how a base class pointer can call a virtual function in the appropriate derived class, depending on the actual object.
Syntax of the Virtual Function
class Base {
public:
virtual void show() {
// base class version
}
};
Example:
Output:
Explanation: In this code, the Animal class has a sound() function, and is marked as virtual, so it can be overridden in derived classes. The Dog class gives its own version of sound(). Even though we use an Animal* pointer, it points to a Dog, so the Dog’s sound() gets called.
B. Function Overriding
When a child class has a function with the same name and parameters as the parent class, and also gives its own definition, it is called function overriding. The right implementation of the function is chosen when the program runs, not when it is compiled, hence it is used in runtime polymorphism.
Rules for Function Overriding:
- The function name in both classes must be the same.
- The parameters must be the same.
- Return type should also be the same.
Function overriding can be achieved in the following ways:
i.) Function Overriding without Virtual Function in C++
If a child class changes a function from the parent class, it will not be used when you call it through a parent class pointer, unless the function is marked as virtual. Hence, without the virtual keyword, C++ looks at the type of the pointer, not the actual object, and decides which function to call before running the program. Hence, the base class version of the function runs even if the object is from the child class.
Example:
Output:
Explanation: In the above C++ code, there is a base class Vehicle and a derived class Car, and both start with a function start(). The base class pointer Vehicle* points to a Car object. But since the start() function in the base class is not marked as virtual, C++ calls the base class version.
ii.) Function Overriding with Virtual Function in C++
When a base class function is marked with the virtual keyword, and the derived class overrides it with the same name and parameters, despite using a base class pointer or reference, the derived class version is called at runtime.
Example:
Output:
Explanation: In this code, the Vehicle class has a start() function, and is marked as virtual, so that it can be changed in other classes. The Car class gives its own version of start(). Even though we use a Vehicle* pointer, it points to a Car, so the Car start() gets called.
Why Use Polymorphism in C++?
Polymorphism in C++ helps the same function to behave in a different way, depending on the object that calls it, which helps to write a common function in a base class and then override it in different child classes as per the need. Also, you don’t have to write a separate code for every type; the correct function gets called automatically at runtime, based on the actual object, not the pointer type. This is called runtime polymorphism and works using virtual functions. It also makes the code flexible, reusable, and easier to manage.
Polymorphism also helps to reduce the duplication of code. Instead of using if-else or switch statements, you can let the object decide how to behave, which makes your program easier to maintain and extend. For example, if you want to add a new class, you don’t have to rewrite the old code. This is very useful in real-world applications like billing systems, games, drawing software, and more.
When To Use Inheritance and Polymorphism in C++?
1. Polymorphism
One should use polymorphism in C++
- When you want to write code that works with different object types.
- When you are using a virtual function in the base class.
- When the behaviour of one class is the same as that of another class.
- When the different objects share similar actions, like draw() for Circle, Rectangle, and Triangle.
2. Inheritance
One should use inheritance in C++
- When different classes have to share a similar function or data.
- When you want to change an existing behaviour of the class without rewriting it.
- When the objects follow the same basic structure.
- When one class is a type of another class, like a Car is a Vehicle, and a Dog is an Animal.
Difference Between Runtime and Compile-Time
Feature |
Compile-Time |
Runtime |
When it happens |
Before running |
While running |
Type of errors |
Spelling/typing error |
Mistakes during the run |
Checking type |
Checked early |
Checked later |
Polymorphism type |
Overloading |
Overriding |
Stage |
Build time |
Execution time |
Example error |
int x = “text”; |
int x = 5/0; |
Conclusion
From the above article, we conclude that polymorphism in C++ lets the same function or operator behave differently, based on the actual object at runtime. It has two main categories, i.e., compile-time polymorphism, like function and operator overloading, and runtime polymorphism, like virtual functions and function overriding. It helps you reuse the code and makes the program clean. It is widely used in real-world applications, where the behaviour has to be changed, based on the type of the object.
FAQs on Polymorphism in C++
Q1. What is polymorphism with an example?
Polymorphism means that one thing can behave in different ways. For example, the + operator can add numbers or join strings.
Q2. Is overloading a type of polymorphism?
Yes, overloading is a compile-time polymorphism.
Q3. What is encapsulation in C++?
Encapsulation means putting related data and functions together in one unit called a class.
Q4. What is the 'this' pointer in C++?
The ‘this’ pointer holds the address of the current object calling the function.
Q5. What is inheritance in C++?
Inheritance lets one class use features of another, helping reuse and extend code easily.