next up previous
Next: Problems Up: TwelfthWeek Previous: Argument Passing

Function Overloading

Here's a function that returns the absolute value of its argument:
int abs(int i) {
    if(i >= 0)
        return i;
    return -i;
    }

But is it only integers that have absolute values? Certainly not. We'd like to have a function that gives the absolute value of a double, too. So we define it. But do we have to give this new function a different name so as not to clash with the version that operates on an int? As it turns out, no - you can give the second funtion the same name:

double abs(double i) {
    if(i >= 0)
        return i;
    return -i;
    }
When you call abs(), the compiler looks at the argument type to determine which variant of abs() to call:
int i = 2;
double j =4;
cout << abs(i);	//calls the int version, since the argument i is an int.
cout << abs(j);	//calls the double version, since the argument j is a double.

To make this clear, you can add statements in the two versions of abs() that print "int version called" and "double version called".

Note that the two functions are defined within the same scope (the global scope) and are distinguished based on argument types (the return type is not taken into consideration). This is different from the previous examples where variables were in different scopes and the one defined in the innermost scope is chosen.

Function overloading is useful when we need to write functions that perform similar tasks but need to operate on different data type.

Here's another example:

void swap(int &x, int &y) {
    int tmp = x;
    x = y;
    y = tmp;
    return;
    }

void swap(double &x, double &y){
    double tmp = x;
    x = y;
    y = tmp;
    return;
    }
If there was no function overloading, we would have been forced to choose a different name for this function.


next up previous
Next: Problems Up: TwelfthWeek Previous: Argument Passing
cs101 senior TA 2005-10-24