Function overloading is also called function polymorphism. Poly means 'any' and morph means 'form': a polymorphic function is many-formed.
Function polymorphism refers to the capability to 'overload' a function with more than one meaning. By changing the number or type of parameters, you can give two or more functions the same function name, and the right one will be called by matching the parameters used. This enables you to create a function that can average integers, doubles and other values without having to create individual names for each function.
Suppose you write a function the doubles whatever input you give it. You would like to be able to pass in an int, a long, a float or a double. Without function overloading, you would have to create four function names:
int DoubleInt(int);
long DoubleLong(long);
float DoubleFloat(float);
double DoubleDouble(double);
With function overloading, you make this declaration:
int Double(int);
long Double(long);
float Double(float);
double Double(double);
This is easier to read and to use. You do not have to worry about which one to call, you just pass in a variable and the right function is called automatically.
The following code demonstrates the use of function overloading:
// example of function polymorphism
#include <iostream.h>
int Double(int);
long Double(long);
float Double(float);
double Double(double);
int main()
{
int myInt = 6500;
long myLong = 65000;
float myFloat = 6.5F;
double myDouble = 6.5e20;
int doubledInt;
long doubledLong;
float doubledFloat;
double doubledDouble;
cout << "myInt = " << myInt << endl;
cout << "myLong = " << myLong << endl;
cout << "myFloat = " << myFloat << endl;
cout << "myDouble = " << myDouble << endl;
doubledInt = Double(myInt);
doubledLong = Double(myLong);
doubledFloat = Double(myFloat);
doubledDouble = Double(myDouble);
cout << "doubledInt = " << doubledInt << endl;
cout << "doubledLong = " << doubledLong << endl;
cout << "doubledFloat = " << doubledFloat << endl;
cout << "doubledDouble = " << doubledDouble << endl;
return 0;
}
int Double (int original)
{
return 2 * original;
}
long Double (long original)
{
return 2 * original;
}
float Double (float original)
{
return 2 * original;
}
double Double (double original)
{
return 2 * original;
}