To understand function overloading, we need to understand the concept of polymorphism. Polymorphism means having many or multiple forms. There are two type of polymorphism.
1) Static Polymorphism
2) Dynamic Polymorphism
Function overloading comes under static Polymorphism. Function overloading means functions with same name but different number or type of arguments.
Let us understand with the help of example.
#include <iostream>
using namespace std;
class base {
public:
void display(int num) {
cout << "Num: " << num << endl;
}
void display(int num1, int num2 = 10) {
cout << "Num1: " << num1 << "Num2: " << num2 << endl;
}
void setValue(int num) {
cout << "int Num: " << num << endl;
}
void setValue(float num) {
cout << "Float Num: " << num << endl;
}
static void displayValue(int num) {
cout << "static int Num: " << num << endl;
}
static void displayValue(int num1, int num2) {
cout << "static Num: " << num1 << endl;
}
void displayInt(int num) {
cout << "static int Num: " << num << endl;
}
void displayInt(int& num) {
cout << "static Num: " << num << endl;
}
};
int main()
{
base b;
int i = 10;
b.display(10); //Error: Ambiguous, Reason: Since both the display candidates fits here
b.display(10, 20);
b.setValue(50);
b.setValue(10.0); //Error: Ambiguous, Reason: By default, this is double and double can be converted to float or int
b.setValue(10.0f);
b.displayValue(10);
b.displayInt(i); // Error: Ambiguous, Reason: Based on whether argument is caught with or without reference, does not result in overloading.
return 0;
}
When code is compiled, each function is assigned particular address. Now, how can same address be assigned to two or more function having same, but differ only in arguments?
Actually compiler performs name mangling i.e. internally function name is converted to different name based on the number and type of argument. That is how every function will have a different name.
For the following scenarios, function overloading is not possible
1) Difference in Return Type
int getValue() {}
void getValue() {}
The above two functions have same prototype except return type. Such kind of function cannot be overloaded.
2) Difference in constness of the parameter
void display(int num) {}
void display(const int num) {}
3) Difference in static keyword
void display(int num) {}
static void display(int num) {}