by John
Kopp
Welcome to About.com's free tutorial on C++ programming.
This lesson covers overloaded functions. Function overloading provides a way to have
multiple functions with the same name. Why would this be of
benefit? Let's look at a simple example. Suppose it's needed
to have a function that converts a temperature from Fahrenheit
to Celsius.
Prototype (Declaration):
void ConvertFToC(float f, float &c);
| Definition:
void ConvertFToC(float f, float
&c) { c = (f - 32.) *
5./9.; } | Now suppose that a
Convert function is also needed to convert an integer
Fahrenheit temperature to Celsius in the same program. One
approach would be to give this function a new name, and
perhaps to update the name of the "float" version as
well.
void fConvertFToC(float f, float &c); void
iConvertFToC(int f, int &c);
| That's not too bad. There are
only two function names to keep track off. Now suppose that a
higher precision, double, version is needed, or a version for
data type short or long.
void fConvertFToC(float f, float &c); void
iConvertFToC(int f, int &c); void
dConvertFToC(double f, double &c); void
lConvertFToC(long f, long &c); void
sConvertFToC(short f, short &c);
| As can be seen, this is quickly
becoming a lexical nightmare. It is now necessary to
remember five different function names for functions that
essentially perform the same calculation. Someone reading or
maintaining a program using these functions is bound to become
quickly confused. It is not clear that exactly how exactly how
each differs. Are only the data types different or are there
differences in calculation? Fortunately, function overloading
provides an alternative. The same function name can be used
for multiple functions provided each differs in the number or
type of its parameters. For each call of the function,
the compiler compares the number and type of the
arguments in the call against the parameter
lists of each version of the function. The compiler selects
the appropriate version. This process is call function
resolution. Next
page > Function
Overloading, Continued. > Page 1,
2,
3
|