Function overloading
Function overloading is a C++ programming feature that allows us to have more
than one function having same name but different parameter list
Example:
The parameters list of a function myfunc(int a, float b) is (int, float) which is
different from the function myfunc(float a, int b) parameter list (float, int).
Function overloading is a compile-time polymorphism.
Now that we know what is parameter list. The rules of overloading: we can have
following functions in the same scope.
sum(int num1, int num2)
sum(int num1, int num2, int num3)
sum(int num1, double num2)
The easiest way to remember this rule is that the parameters should qualify any
one or more of the following conditions, they should have different type, number
or sequence of parameters.
Example:
These two functions have different parameter type:
sum(int num1, int num2)
sum(double num1, double num2)
These two have different number of parameters:
sum(int num1, int num2)
sum(int num1, int num2, int num3)
These two have different sequence of parameters:
sum(int num1, double num2)
sum(double num1, int num2)
All of the above three cases are valid case of overloading. We can have any
number of functions, just remember that the parameter list should be different.
In Below example even though they have different return types, its not valid.
This is not allowed as the parameter list is same.
Example:
int sum(int, int)
double sum(int, int)
program of Function overloading
#include<iostream.h>
#include<conio.h>
void print(int i)
{
cout << " Here is int " << i << endl;
}
void print(double f)
{
cout << " Here is float " << f << endl;
}
int main() {
clrscr();
print(10);
print(100.20);
getch();
return 0;
}