Function Overloading

One of the main advantages of writing functions is the ability to make chunks of code reusable.

int temp = x;
x = y;
y = temp;

Can become:

void swap(int &num1, int &num2)
  {
  int temp = num1;
  num1 = num2;
  num2 = temp;
  }

Those three lines of code can then be used wherever they are needed simply by calling the function and passing the necessary arguments.

int x = 11, y = 22;

swap (x, y);
.
.
.
int w = 335, z = 444;

swap (w, z);
.
.
.
int a = 5005, b = 6006;

swap (a, b);

Since the values to be exchanged are passed to the function and the new values passed back from it, this function can be used to exchange the values of any two integer variables.

What if we wanted to swap two doubles? or char?

In C, we would have had to write a second function that takes two double arguments and also has a different name.

void realSwap(double &num1, double &num2)
  {
  double temp = num1;
  num1 = num2;
  num2 = temp;
  }

C++ provides the ability to have multiple functions with the same name. This is known as function overloading.

Since the functions have the same name, there has to be some way for the compiler to distinguish between them. The argument list is used to distinguish one function from another.

Criteria for distinguishing:

  1. the order of the arguments
  2. the data type of the arguments
  3. the number of arguments
void swap(int &num1, int &num2)
  {
  int temp = num1;
  num1 = num2;
  num2 = temp;
  }


void swap(double &num1, double &num2)
  {
  double temp = num1;
  num1 = num2;
  num2 = temp;
  }


int x = 9, y = 30;
double a = 1.239, b = 3.14;

swap (x, y);
swap (a, b);

Notice that the return type is not one of the criteria.

An informal rule to follow:

Functions with the same name should do the same thing.