4.1. Function overloads

Unlike C, in C++, two different functions can have the same name as long as their parameter lists are different. When two functions have the same name, but different parameters, the functions are said to be overloaded.

In order to count as a valid overload, either the number of parameters must be different, or the parameter types must be different, or a combination of both. For example:

Function overloads are a huge advantage over C where (nearly) every function is global and every function name must be unique. For example:

This just adds to the amount of stuff programmers have to commit to memory. In C++, you only have to remember a single function to compute the absolute value: abs.

Another example: a family of functions to compute volume.

Note

The return type is not part of the overload.

Two functions in the same namespace that differ only in return type will not compile.

4.1.1. Overloading anti-patterns

How many parameters are too many?

This is an often asked question, with no clear cut answer. It is primarily a question of clarity and design.

For example, given:

int operate (float a, int b, long c, double d);

In this case, the parameters and function name provide no guidance on how to call this function. So four is probably too many parameters, simply because future usage errors are likely.

Keep in mind that more parameters equal more complexity. Limit the number of parameters you need in a given method, or use a struct to combine parameters. Also, be wary of overloads with the same number of parameters and different types. For example:

int operate (double a, int b);
int operate (int a, double b);

Depending on what operate does with it’s parameters, reversing the order of the parameters could have drastic consequences. We just don’t know without looking at the source code. In this case even two parameters is too many. It is almost certain someone will invoke the wrong version occasionally.


More to Explore

You have attempted of activities on this page