Function/Variable Scope   «Prev  Next»
Lesson 4 Overloading functions
Objective Overloading a C++ function

Function Overloading in C++

C++ Function
Discover what overloading a function means in C++.
The choice of a function name is to indicate the function's chief purpose. Readable programs have a literate choice of identifiers. Sometimes different functions are used for the same purpose.
Overloading refers to using the same name for multiple meanings of a function. The meaning selected depends on the types of the arguments used by the function.


Let us look at some code that overloads the function avg_arr(). This function averages the values in an array of double or in an array of int.

//Average the values in an array.
double avg_arr(const int a[], int size){
 int  sum = 0;

 for (int i = 0; i < size; ++i)
  sum += a[i]; //int arithmetic
 return (static_cast<double>(sum) / size);

double avg_arr(const double a[], int size){
 double  sum = 0.0;
 for (int i = 0; i < size; ++i)
  sum += a[i]; //double arithmetic
 return (sum / size);

Thinking in C++
You can invoke avg_arr() like this:
int main(){
 int w[5] = { 1, 2, 3, 4, 5 };
 double  x[5] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
 cout << avg_arr(w, 5) << " int average" << endl;
 cout << avg_arr(x, 5) << " double average" << endl;

The compiler chooses the function with matching types and arguments.

A function name is overloaded if there are different versions of the function, distinguished by their parameter types.


When the same function name is used for more than one function, then the name is overloaded. In C++ you can overload function names provided the parameter types are different. For example, you can define two functions, both called print, one to print an employee record and one to print a time object:
void print(Employee e) ...
void print(Time t) ...

When the print function is called,

the compiler looks at the type of x. If x is an Employee object, the first function is called. If x is a Time object, the second function is called. If x is neither, the compiler generates an error. When it comes to constructors, C++ demands that the name of a constructor equal the name of the class. If a class has more than one constructor, then that name must be overloaded. In addition to name overloading, C++ also supports operator overloading. You can define new meanings for the familiar C++ operators such as +, ==, and , provided at least one of the arguments is an object of some class. For example, we could overload the > operator to test whether one product is better than another.