Function overloading in c++


Function overloading:

In c++ two or more function having the same name but the different parameter is called function overloading.
           To see why function overloading is important, first consider three functions defined by the c subset: abs(), labs(),  and fabs() . The abs() functions returns the absolute value of an integer, labs()  returns the absolute value of long, and fabs()  returns the absolute value of double.
Ex:
#include <iostream>
using namespace std;
// abs is overloaded three ways
int abs(int i);
double abs(double d);
long abs(long l);
int main()
{
cout << abs(-10) << "\n";
cout << abs(-11.0) << "\n";
cout << abs(-9L) << "\n";
return 0;
}
int abs(int i)
{
cout << "Using integer abs()\n";
return i<0 ? -i : i;
}
double abs(double d)
{
cout << "Using double abs()\n";
return d<0.0 ? -d : d;
}
long abs(long l)
{
cout << "Using long abs()\n";
return l<0 ? -l : l;

}


Output:



Using integer abs()

10

using double abs()

11

using long abs()

9




Here an overloaded function is abs.  as you can see, at the above program function name abs are the same for three functions, but the parameter type(int, long, double) differs.

In General, overload a function, simply declare the different version of it. You must observe one important restriction when overloading a function that is, the number of the parameters of each overloaded function must differ.

Recommended Posts:

Post a Comment

2 Comments