Function Overloading

In C++, two or more functions can have the same name in a program. There has to be some way for the compiler to figure out which one you are calling. Therefore, there must be some difference in either the number of parms or the type of at least one of the parms. A different return type is not sufficient to distinguish two functions -- there must be some difference in the parameter list. This feature is called function overloading.

The function name along with the type of each parm is known as the function signature. If there is more than one function with a given signature, the compiler will generate an error.

Sample Program with Overloading


int max(int,int);
int max(int,int,int);
int max(double,double);

int main()
{
   int first,second,third;
   double fdoub,secdoub;

   cout << "Enter three ints: ";
   cin >> first,second,third;
   cout << "Enter two real numbers: ";
   cin >> fdoub, secdoub;

   cout << "Max of " << first << " and " << second << " is "
        << max(first,second);
   cout << "Max of " << first << ", " << second << " and "
        << third << " is " << max(first,second,third);
   cout << "Max of " << fdoub << " and " << secdoub << " is "
        << max(fdoub,secdoub);
   return 0;
}

int max(int a,int b)
{
   if (a > b)
      return a;
   return b;
}

int max(int a,int b,int c)
{
   if (a > b && a > c)
      return a;
   if (b > c)
      return b;
   return c;
}

double max(double a,double b)
{
   if (a > b)
      return a;
   return b;
}

Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2006