Function Overloading

Sometimes you have related functions that do the same thing, but behave differently depending on inputs. For example:

int main() {
  int h,w,r;
  bool square, circle;
  // pretend the vars above get assigned per user input
  if (square) {
    cout << areaOfSquare(h, w);
  } else if (circle) {
    cout << areaOfCircle(r);
  }
}

int areaOfSquare(int h, int w) {
  return h * w;
}

double areaOfCircle(int r) {
  return 3.14 * r * r;
}

Both of these functions compute area. The difference between the two functions depends on inputs, and also how they are computed. But they both compute area. Rather than having main() call two different functions with two different names, you could have two area() functions with the same name but with different inputs and implementations. For example:

int main() {
  int h,w,r;
  bool square, circle;
  // pretend the vars above get assigned per user input
  if (square) {
    cout << area(h, w);
  } else if (circle) {
    cout << area(r);
  }
}

int area(int h, int w) {
  return h * w;
}

double area(double r) {
  return 3.14 * r * r;
}

Kind of a silly example, since you still do an if-check in main, but do you notice that you have two functions with the same name that receive different parameters (different types and/or number of params)? How does the program know which function you mean? Because C++ supports function overloading.

Function Overloading

We say that you 'overload a function' when you declare multiple functions with the same name but different parameters (we say that the functions have different 'signatures').

int main() {
  // some imaginary logic
  area(2, 3); // which area()? (the first one) Why? (passing two int parameters)

  area(4.2, 6.9); // which area()? (the middle one) Why? (passing two double parameters)

  area(2.0); // which area()? (the last one) Why? (passing one double parameter)
}

int area(int h, int w) {
  return h * w;
}

int area(double h, double w) {
  return h * w;
}

double area(double r) {
  return 3.14 * r * r;
}

An example of this in real use is illustrated by the assignment OverloadedInputValidation. Two functions with the same name, but different parameter lists ("two functions with different signatures").

There is more to function overloading, but these fundamentals are all you need.


See p359 - 260 in our textbook (beware though, it's within the context of classes and constructors; we'll talk about those on Monday).

---