In this article we are going to talk about function overloading, a concept already mentioned before. Function overloading (or method overloading) is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call. If you remember, we've explained a similar mechanism when we talked about constructors: we were able to write multiple constructors, as long as their signatures (argument lists) were different.
When you call an overloaded function, the compiler determines the most appropriate function definition by comparing the argument lists. This process is called overload resolution.
A good practice when overloading functions is:
If two functions have the same name, they should perform the same kind of task (and vice versa).
This is the so-called rule of semantics preservation
As we said, overloaded functions must have different number of arguments, and/or different types of arguments. Return types can be the same, but don't have to be. It isn't enough to have different return types as the only difference between two functions.
Let's give one common example of utilizing function overloading. We will write multiple functions for calculating the volumes of different objects.
using namespace std;
// volume of a cube
int volume(int s)
// volume of a cylinder
double volume(double r, int h)
// volume of a sphere
double volume(double r)
cout << volume(10) << endl;
cout << volume(2.5, 8) << endl;
cout << volume(4) << endl;
If you run the program, you will see that the correct versions of the functions were called (since there was no ambiguity - all of the three argument lists were different). In the next article we will continue with operator overloading. The idea is similar, but the implementation will be a bit more complicated because different groups of operators are overloaded differently. Operator overloading is a powerful feature, and we'll make sure to cover it in detail.