Source Code. Projects. Nerd Stuff. Art Stuff.

Lesson 2: Function Name Overloading

Function Name Overloading

Overloading Function Names (Sec. 3.6)

Overloading is when you have two or more functions with the same name but different parameters. Those parameter differences can be in the number or type of the parameters.

For example, imagine you have a function to calculate the inflation rate for a year. The function has two parameters: the price of an item at the beginning of the year, and the price at the end of the year. Here’s a prototype for that function:

1
  float inflationRate(float priceYr1, float priceYr2); // function 1

But what if you also want a function to calculate the average annual inflation rate when you have two prices for an item that aren’t exactly one year apart? You can define another function to do this, using the same name:

1
  float inflationRate(float priceYr1, float priceYr2, float numYears); // function 2

Both of these functions can be definded and used within one program. The key here is not to get confused by the function names. Overloaded functions share a name only. They are completely distinct. The compiler can tell them apart because they have different numbers of parameters.

You could have another version of the function as well, this one distinct from the others in the data type of the parameters:

1
  float inflationRate(char price1[], char price2[]); // function 3

Here the prices are character arrays (cstrings) which the function would have to convert to numeric data in order to perform a calculation.

So if all three of the above functions are defined in the same program, the function call:

1
  inflationRate(1.50, 1.60)

would call the version labeled “function 1″ above, the function call:

1
  inflationRate(1.50, 1.75, 1.8)

would call the version labeled “function 2″ above, and the function call:

1
  inflationRate("1.50", "1.60")

would call the version labeled “function 3″ above. These are three distinct functions that happen to share a name.

Note: The following differences between functions are not sufficient to allow for overloading (because function calls don’t uniquely identify these criteria):

  • Different return types
  • Different parameter names
  • Call-by-reference vs. Call-by-value parameters (including the & in one function but not in another)

Here is a sample program that uses function name overloading: Hospital program: has two different functions with the same name.