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, Time and American, using structures with the same names. Furthermore, both programs have a print function. Imagine that a programmer writes a client program using both structures. How does the compiler "know" which print function we mean when we call it? The older C programming language resolved the problem by requiring the two functions to have different names. C programmers gave the functions similar names because they perform similar tasks: printing a specific structure's fields:print_time and print_american. C++ offers a more elegant solution.
C++'s' solution, even in the absence of object-oriented features, is overloading the print function, requiring each to have a unique parameter list.
void print(Time t) { . . . . } void print(American am) { . . . . } |
Time t; American a; . . . . print(t); // the Time print function print(a); // the American print function |
void make_time(int h, int min, int s) { . . . . } |
void make_time(int s) { . . . . } |
By Value | By Reference |
---|---|
void print(Time t){ ... } |
void print(Time& t){ ... } |
(a) | |
print(now); |
print(now); |
(b) |