Overloading Function Names

  1. Giving two, or more different function definitions to the same function name is allowed in C++.

  2. This is called overloading the function name.

  3. These various function definitions must have either (a) different number of formal parameters, or (b) some formal parameters are of different types.

  4. When an overloaded function is called, the compiler uses the function definition whose (a) number of formal parameters, and (b)the types of formal parameters match the arguments in the function call.

  5. If these various function definitions all have the same number of formal parameters, and the types of parameters all match, then there is no way the compiler can tell from your function call which of the function definitions to use.

  6. //Illustrates overloading the function name ave,
    to accept either two or three parameters.

    #include <iostream>
    using namespace std;

    double ave(double n1, double n2);
    //Returns the average of the two numbers n1 and n2.

    double ave(double n1, double n2, double n3);
    //Returns the average of the three numbers n1, n2, and n3.

    int main( )
    {
         cout << "The average of 2.0, 2.5, and 3.0 is "
             << ave(2.0, 2.5, 3.0) << endl;

         cout << "The average of 4.5 and 5.5 is "
             << ave(4.5, 5.5) << endl;

         return 0;
    }

    double ave(double n1, double n2)
    {
         return ((n1 + n2)/2.0);
    }

    double ave(double n1, double n2, double n3)
    {
         return ((n1 + n2 + n3)/3.0);
    }

  7. This example involves overloading functions having the same number of parameters, but different data types.

    // The standard library has an integer function abs(x) that computes
    // the absolute value of an integer, x. It is defined in cstdlib
    #include <iostream>
    #include <cstdlib>
    using namespace std;

    double abs(double x);
    long abs(long x);
    float abs (float x);

    int main ( )
    {
         int an_integer;
         long a_long;
         float a_float;
         double a_double;

         cout.setf(ios::fixed|ios::showpoint);
         cout <<"Enter an integer, a long, a float and a double.\n";
         cin >> an_integer >> a_long >> a_float >> a_double;
         cout << "abs for an integer " << abs(an_integer) << endl;
         cout << "abs for a long " << abs(a_long) << endl;
         cout.precision(7);
         cout << "abs for a float " << abs(a_float) << endl;
         cout.precision(15);
         cout << "abs for a double " << abs(a_double) << endl;

    return 0;
    }

    long abs (long x)
    {
         return (x > 0 ? x: -x);

    }

    float abs (float x)
    {
         return (x > 0 ? x: -x);
    }

    double abs (double x);
         return (x > 0 ? x: -x);
    }