The word polymorphism means having many forms. 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 exhibits different behaviour in different situations. This is called polymorphism.
In C++, polymorphism concept can be applied to functions and operators. A single function can work differently in different situations. Similarly, an operator works different when used in different context.
Types of Polymorphism
Polymorphism in C++ can be classified into two types:
- Compile-time Polymorphism
- Runtime Polymorphism
Types of Polymorphism1. Compile-Time Polymorphism
Also known as early binding and static polymorphism, in compile-time polymorphism, the compiler determines how the function or operator will work depending on the context. This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but behave differently for different parameters. Such functions are said to be overloaded; hence, this is known as Function Overloading. Functions can be overloaded either by changing the number of arguments or changing the type of arguments.
Example:
C++
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
// Function to add two integers
void add(int a, int b) {
cout << "Integer Sum = " << a + b
<< endl