Overloading means that a programmer can reuse a name or symbol that already has a defined meaning in the current scope, giving it a new meaning. C++ allows programmers to overload functions by declaring two or more of them with the same name in the same scope. However, functions declared in different scopes (e.g., in different classes or namespaces - detailed in Chapter 9) are not considered overloaded. The only other requirement for successfully overloading functions is that each must have a unique parameter list. The compiler does not consider function return types for overloading; they may be the same or different.
The programming examples presented at the end of Chapter 5 included two similar programs that use similar structures: Time and American. Furthermore, the header files for each structure have a prototype for a print function. Imagine a programmer writing a client program that uses both structures. How does the compiler "know" which print function we mean when we call it? The C programming language resolved the conflict with the requirement that all functions have unique names. When the functions performed similar tasks but with different data, C programmers often named them similarly. For example: print_time and print_american. C++ offers a more elegant solution.
Function overloading is "more elegant" than and superior to multiple function names in two ways. First, it allows programmers to use a single function name to denote various functions that perform essentially the same tasks but with different data types. Using function overloading, programmers can concisely match a function's name to its purpose. Second, it eliminates the inevitable "clutter" that arises from multiple names. The following examples demonstrate three common function-overloading patterns.
| Defining Overloaded Functions | Calling Overloaded Functions |
|---|---|
void print( |
Time |
| Defining Overloaded Functions | Calling Overloaded Functions |
|---|---|
void make_time( |
int t; int x; int y; int z; . . . make_time( |
int function(double x, double y, double z,Time t , int a, int b, int c); int function(double x, double y, double z,American a , int a, int b, int c);
int function(double x);double function(double x); // error - incorrect overload
| By Value | By Reference |
|---|---|
void print(Time t){ ... } |
void print(Time |
| (a) | |
print(now); |
print(now); |
| (b) | |