Pages

Sunday, July 17, 2011

Function Overloading

he overloaded functions in the previous example differed in the type of their arguments. It is also possible to overload functions if their number of arguments differs. For example:
float FindMax(float a, float b);
float FindMax(float a, float b, float c);
int FindMax(int a, int b);
and so on.

Functions differing only in their return type cannot be overloaded. Since the returned value may be implicitly converted, the compiler cannot resolve which version the programmer intended to use. The following code causes a compilation error.

int FindAverage(float a, float b, float c);
    //Returns a rounded "average" as an int
float FindAverage(float a, float b, float c);
    //Returns the double average

int main()
{

    int avg;
    float a = 5.0;
    float b = 5.5;
    float c = 6.0;

    avg = FindAverage(a, b, c);

    return 0;
}

The compiler cannot determine whether the programmer intended:
1) To use the float version of FindAverage and then truncate the return value and assign to avg.
2) To use the int version of FindAverage, which returns a rounded average as an int.


Cases where overloading should not be used
1) If the functions to be overloaded perform distinct operations, then overloading will mask this uniqueness and make their proper use harder.

Suppose there are two functions to find a minimum value, one for float arguments and another for integer arguments. Further suppose that the minimum value function for integers is to return either the minimum, or zero if the minimum is less than zero, while the minimum value function for floats returns the minimum regardless of sign. If they are implemented as overloaded functions then it is easy to forget the extra bound on the integer version.

Use:
int FindMinOrZero(int a, int b);    //Or some similar name
float FindMin(float a, float b);

Rather than:
int FindMin(int a, int b);
float FindMin(float a, float b);

This distinct functionality is more apparent using distinct identifiers.

2) A single function with default arguments can replace the overloaded functions.
Suppose that an "integer" FindMax function is needed and that it can take either two or three arguments. Also, assume that if will return zero if all the arguments are negative. 

Use:
float FindMax(float a, float b, float c = 0);

Rather than:
float FindMax(float a, float b);
float FindMax(float a, float b, float c);

This results in only a single function to learn to use and to maintain. 
3) Function templates offer a cleaner design.
Function templates are covered in the next lesson. They offer a way to parameterize arguments that differ only by type. The net result is that a single function template can sometimes replace several overloaded versions of a function.

0 comments:

Post a Comment