Overloading and default arguments
The function int twice(int x) doubles integers, while 1.25 needs the same function for double. It does not need a different name: in C++ both functions can be called twice:
#include <iostream>
int twice(int x) {
return x * 2;
}
double twice(double x) {
return x * 2;
}
int main() {
std::cout << twice(21) << ' ' << twice(1.25) << '\n'; // 42 2.5
}For 21 the compiler calls the int version, and for 1.25 the double version.
Different parameter lists
Overloading means several functions with one name and different parameter lists. The lists must differ in the number of parameters or in their types. The twice functions above differ in parameter type, while max(int a, int b) and max(int a, int b, int c) differ in their number. The return type plays no part: functions that differ only in it do not compile.
int parse(int x);
double parse(int x); // ✗error: functions that differ only in their return type cannot be overloadedThe compiler picks a function by the call's arguments alone, and parse(5) does not show which of the two results is wanted.
Choosing an overload
If nothing matches exactly, the compiler ranks how the argument converts to the parameter of each overload. An exact match beats a promotion, and a promotion beats a conversion. A promotion widens float to double, or a small integer type such as short to int. Any other change of type, like float → int, is a conversion.
That is why an argument of type short goes to twice(int), not to twice(double). The literal 2.5f has type float, while 2.5 is a double.
If the two best overloads are equally good, the call is ambiguous, and the program does not compile. That happens with an argument of type long: long → int and long → double are both conversions.
Optional arguments
A parameter can have a default argument: a value the compiler supplies when the call leaves that argument out:
#include <iostream>
int power(int base, int exp = 2) {
int result = 1;
for (int i = 0; i < exp; ++i) {
result *= base;
}
return result;
}
int main() {
std::cout << power(5) << ' ' << power(2, 10) << '\n'; // 25 1024
}The compiler turns the call power(5) into power(5, 2). No overload is needed here: there is one function, and it can be called with one argument or with two.
Common mistake
A default value is given to a parameter that is followed by a parameter without one:
int power(int base = 2, int exp); // ✗error: missing default argument on parameter 'exp'This is a compiler error: after a parameter with a default value, every following parameter must have one too. Otherwise the call power(3) would not show which parameter gets 3. Move such parameters to the end of the list.