next up previous
Next: Recursion Up: Functions Previous: Local/Global

Function Overloading

In C++ two or more functions can share the same name as long as their parameter declarations are different. In this situation the functions that share the same name are said to be overloaded, and the process is referred to as function overloading.

Example
//Overload a function three times
#include <iostream.h>

void f(int i); //integer parameter
void f(int i, int j);// two integer parameters
void f(double k); // one double parameter

main()
{
f(10); // call f(int i)
f(10,20); //call f(int i,int j)
f(12.35); //call f(double k)
return 0;
}
void f(int i)
{
cout << "In f(int i), i = "<<i<<'$\backslash$n';
}
void f(int i, int j)
{
cout <<" In f(int i, int j), i="<<i;
cout <<",j="<<j<< '$\backslash$n';
}
void f(double k)
{
cout << "In f(double k), k="<<k<< '$\backslash$n';
}

As you can see f() is overloaded three times.

It is possible to create a situation in which the compiler is unable to choose between two or more correctly overloaded functions. When this happens, the situation is said to be ambiguous. Ambiguous statements are errors and programs containing ambiguity will not compile.

Example
// Overloading ambiguity
#include <iostream.h>
float f(float i);
double f(double i);
main()
{
//unambiguous, calls f(double)
cout <<f(10.3) << " ";
//ambiguous
cout <<f(10);
return 0;
}
float f(float i)
{
return i;
}
double f(double i)
{
return -i;
}

Here, f() is overloaded so that it can take arguments of either type float or double. When f is called using integer 10, ambiguity is introduced because the compiler has no way of knowing whether is should be converted to a float or double both are valid conversions This confusion causes an error message to be displayed and prevents the program from compiling.


next up previous
Next: Recursion Up: Functions Previous: Local/Global
Yousef Haik
2/23/1998