One operation, several parameter lists
Function overloading allows functions with the same name when their parameter lists differ in a way the language can distinguish. The compiler selects an overload from the arguments at the call site. A return type alone cannot distinguish two ordinary function overloads.
Complete example
#include
#include
void show(int value) {
std::cout << "integer: " << value << '\n';
}
void show(double value) {
std::cout << "real: " << value << '\n';
}
void show(const std::string& value) {
std::cout << "text: " << value << '\n';
}
int main() {
show(7);
show(2.5);
show(std::string{"C++"});
} Expected lines: integer: 7, real: 2.5 and text: C++. The exact argument types make these choices straightforward.
Conversions can introduce ambiguity
Given void process(long) and void process(double), a call with an int argument can be ambiguous because neither conversion is a uniquely better match. Do not patch every ambiguity with a cast before asking whether the interface itself is clear. Use explicit types at boundaries and remove overlapping overloads when they add no useful meaning.
What does not create a new overload
Changing only a parameter name does nothing: void f(int x) and void f(int y) declare the same function. Top-level const on a by-value parameter does not produce a separate function either. References to const and non-const objects can participate in distinct overloads, but callers should not need to memorize a complicated set of rules just to use a simple operation.
Overloading versus overriding
Overloading chooses among parameter lists, usually at compile time. Overriding supplies a derived-class implementation of a virtual member function with the matching signature. These are different mechanisms. A similarly named derived function with different parameters can hide base-class names instead of overriding the intended virtual function; override helps detect mistakes.
Exercises and answers
- Create area(int side) and area(int width, int height). For area(4) expect 16; for area(4, 3) expect 12.
- Can int compute(int) coexist with double compute(int) as a different overload? No, the return type alone is insufficient.
- Add show(char). show('A') should now select the character overload rather than promoting the character to int.
- Combine a one-parameter overload with another using a default second parameter; identify which calls become ambiguous and redesign them.