Background
C++ was designed from the beginning as a language that supports function overloading — the ability to declare multiple functions with the same name but different parameters. This allows for creating a readable and convenient API.
Problem
When there are many functions with the same name, the compiler needs to choose the appropriate implementation among all overloaded ones, considering argument types, conversions, default parameters, and references. Careless overloading can lead to ambiguities and elusive errors.
Solution
The compiler selects the function based on the best match of the argument sequence, type match accuracy, and minimal conversions. However, nuances must be taken into account: if there are significant conversions or default arguments, one might unexpectedly encounter ambiguity.
Code example:
void foo(int x); void foo(double x); void foo(int x, int y = 0); foo(5); // will call void foo(int x) because it's an exact match foo(5.2); // will call void foo(double x) foo(5, 6); // will call void foo(int x, int y)
Key features:
Can functions be overloaded only by return type?
No. Overloading is possible ONLY by the type and number of parameters; the return type does not participate in overload resolution.
int foo(); double foo(); // Error: overloading only by return type is not possible!
How does the compiler choose which overloaded function to call if all parameters can be converted?
The compiler chooses the "best match" — the function that requires the minimum number of type conversions or an exact match. If there is ambiguity, the code will not compile.
void bar(int); void bar(long); bar(1); // int exact match: bar(int) will be called
Can you mix overloads with default arguments and regular overloads?
Yes, but you may encounter call ambiguity if the function signatures overlap.
void test(int x); void test(int x, int y = 10); test(5); // Error: ambiguity — both apply
In a library, overloaded functions with overlapping default arguments lead to compilation errors when updating the code.
Pros:
Cons:
In the project, a convention was established — not to mix overloads with default arguments, or either use only one function with default values or purely overload by unique parameters.
Pros:
Cons: