Function Overloading in C++
One significant addition made to the capabilities of function in C++ is that of function overloading. With this facility you can have multiple functions with the same name, unlike C, where all the functions in a program must have unique names.
In C, every function has to have a unique name. At times this becomes annoying. For example, there are following three different functions that return the absolute value of an argument:
int abs (int i); long labs (long l); double fabs (double d);
All these functions do the same thing, so it seems unnecessary to have three different function names. C++ overcomes this situation by allowing the programmer to create three different functions with the same name. This is called function overloading.
Let us illustrate function overloading with an example as follows:
int max (int, int); int max (int, int, int); //function prototypes int main() { cout << max(99, 77) << " " << max(55, 66, 33); } //function defined int max(int x, int y) { //returns maximum of two given integers return (x > y ? x : y); } int max(int x, int y, int z) { //returns maximum of three given integers int m = (x > y ? x : y); return (z > m ? z : m); }
Here, two different functions, all named “max” are defined. The compiler checks their parameter lists to determine which one to use on each call. For example, the first call [max(99, 77)] passes two int’s, so the version that has two int’s in its parameter list is being called.