Polymorphism is a Greek word meaning "many forms". In programming, it refers to the ability of a single function, object, or operator to behave differently depending on the context.
C++ supports two types of polymorphism:
This section focuses on Compile-Time Polymorphism, where the compiler determines exactly which function to call based on the arguments provided before the program even runs.
Function overloading allows you to have multiple functions in the same scope that share the same name, provided they have different parameter lists (signatures).
The compiler looks at the number, types, and sequence of arguments passed to the function to decide which version to execute.
#include <iostream>
using namespace std;
class PrintUtils {
public:
// Overload 1: Takes an int
void print(int i) {
cout << "Printing int: " << i << endl;
}
// Overload 2: Takes a double
void print(double f) {
cout << "Printing double: " << f << endl;
}
// Overload 3: Takes a string
void print(string s) {
cout << "Printing string: " << s << endl;
}
};
int main() {
PrintUtils pu;
// The compiler knows exactly which function to call based on the argument type
pu.print(10); // Calls print(int)
pu.print(3.14159); // Calls print(double)
pu.print("Hello!"); // Calls print(string)
return 0;
}Note: You cannot overload functions based solely on their return types. The parameter lists must differ.
C++ allows you to redefine how standard operators (like +, -, *, ==) work when applied to custom objects. This is called operator overloading.
For example, you can overload the + operator to add two custom Complex number objects together, just like you would add two integers.
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
// Overloading the '+' operator
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void display() {
The ability of a message or function to be displayed in more than one form.
Polymorphism that is resolved by the compiler before the program runs. Achieved via function overloading and operator overloading.
Having multiple functions with the same name but different parameters (number, type, or order).
Test your understanding with 2 questions
Which of the following is an example of compile-time polymorphism?
Can two overloaded functions differ only by their return type?
2 Modules
2 Modules