FUNCTION OVERLOADING

Suppose you have written a function that determines the maximum value in an array of values of type double:

// Function to generate the maximum value in an array of type double
double maxdouble(double data[], const int& len)
{
   double maximum(data[0]);
        
   for(int i = 1; i < len; i++)
      if(maximum < data[i])
         maximum = data[i];
        
   return maximum;
}

You now want to create a function that produces the maximum value from an array of type long, so you write another function similar to the first, with this prototype:

long maxlong(long data[], const int& len);

You have chosen the function name to reflect the particular task in hand, which is OK for two functions, but you may also need the same function for several other types of argument. It seems a pity that you have to keep inventing names. Ideally, you would use the same function name max() regardless of the argument type, and have the appropriate version executed. It probably won’t be any surprise to you that you can, indeed, do this, and the C++ mechanism that makes it possible is called function overloading.

What Is Function Overloading?

Function overloading allows you to use several functions with the same name as long as they each have different parameter lists. When one of the functions is called, the compiler chooses the correct version for the job based on the list of arguments. Obviously, the compiler must always be able to decide unequivocally which function should be selected in any particular instance of a function ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.