By Stephen R. Davis

Floating-point variables and variables of different size in C++ are passed to functions in the same way that int variables are as demonstrated in the following code snippet. This example snippet passes the value of the variable dArg along with the const double 0.0 to the function maximumFloat().

// maximumFloat - return the larger of two floating
//                point arguments
double maximumFloat(double d1, double d2)
{
    if (d1 > d2)
    {
        return d1;
    }
    return d2;
}
void otherFunction()
{
    double dArg = 1.0;
    double dNonNegative = maximumFloat(dArg, 0.0);
    // ...function continues...

Overloading function names

The type of the arguments are part of the extended name of the function. Thus the full name of the earlier example function is maximumFloat(double, double). You can differentiate between two functions by the number of arguments. You can also differentiate between two functions by the type of the arguments, as shown in the following example:

double maximum(double d1, double2);
int    maximum(int n1, int n2);

When you do the declaration this way, it’s clear that the call maximum(1, 2) refers to maximum(int, int), while the call maximum(3.0, 4.0) refers to maximum(double, double).

Defining functions that have the same name but different arguments is called function overloading.

You can differentiate by the signedness and length as well:

int maximum(int n1, int n2);
long maximum(long l1, long l2);
unsigned maximum(unsigned un1, unsigned un2);

Fortunately, this is rarely necessary in practice.

Mixed-mode overloading

The rules can get really weird when the arguments in the call don’t line up exactly with the declarations. Consider the following example code snippet:

double maximum(double d1, double d2);
int    maximum(int n1, int n2);
void otherFunction()
{
    // which function is invoked by the following?
    double dNonNegative = maximum(dArg, 0);
    // ...function continues...

Here the arguments don’t line up exactly with either declaration. There is no maximum(double, int). C++ could reasonably take any one of the following three options:

  • Promote the 0 to a double and call maximum(double, double).

  • Demote the double to an int and invoke maximum(int, int).

  • Throw up its electronic hands and report a compiler error.

The general rule is that C++ will promote arguments in order to find a match but will not automatically demote an argument. However, you can’t always count on this rule.

Do not rely on C++ to figure out what you mean; instead, make the necessary conversions explicit:

void otherFunction(int nArg1, double dArg2)
{
    // use an explicit cast to make sure that the
    // proper function is called
    double dNonNegative = maximum((double)nArg1, dArg2);

Now it’s clear that you mean to call maximum(double, double).