The Analogy: One Word, Several Tools
In English you open a door, open a bottle and open a bank account. Nobody is confused, because the object tells you which action is meant. You do not need openDoor, openBottle and openBankAccount.
Overloading gives C++ the same convenience: several functions may share a name as long as their parameter lists differ, and the compiler picks the right one from the arguments at the call site. The choice happens at compile time, costs nothing at runtime, and the goal is always the same — one name for one idea, with the details of the input handled quietly.
Syntax or Core Structure
#include <iostream>
#include <string>
#include <vector>
// Same name, different parameter lists.
int area(int side) { return side * side; }
int area(int w, int h) { return w * h; }
double area(double radius) { return 3.14159 * radius * radius; }
void print(int n) { std::cout << "int: " << n << "\n"; }
void print(double d) { std::cout << "double: " << d << "\n"; }
void print(const std::string& s){ std::cout << "text: " << s << "\n"; }
void print(bool b) { std::cout << "bool: " << (b ? "true" : "false") << "\n"; }
int main() {
std::cout << area(4) << "\n"; // 16 -> area(int)
std::cout << area(3, 5) << "\n"; // 15 -> area(int, int)
std::cout << area(2.0) << "\n"; // 12.6 -> area(double)
print(42); // int
print(3.5); // double
print("hello"); // text (const char* converts to std::string)
print(true); // bool
return 0;
}
Overloads may differ by the number of parameters, their types, or their order. They may not differ by return type alone:
int value();
double value(); // ERROR: redefinition -- the call site gives no clue
Technical Depth: How the Compiler Chooses
The resolution ladder
For each call the compiler gathers every visible function with that name, discards the ones that cannot accept the arguments, and ranks the rest. Roughly, best to worst:
- Exact match — the argument type is already the parameter type.
- Trivial adjustment — array-to-pointer decay, adding
const. - Promotion —
char/shorttoint,floattodouble. - Standard conversion —
inttodouble,doubletoint, anything tobool, derived pointer to base pointer. - User-defined conversion — via a converting constructor or
operator T().
If two candidates tie at the same rank, the call is ambiguous and will not compile:
void f(int);
void f(double);
f(5); // exact match on int -- fine
f(5.0); // exact match on double -- fine
f('a'); // promotion to int wins over conversion to double -- fine
f(5L); // long: conversion to int and to double tie -> AMBIGUOUS
The fix is never to guess: add the overload you actually meant (void f(long)) or cast at the call site (f(static_cast<int>(5L))).
The bool trap
Any pointer converts to bool, and that conversion is ranked higher than a user-defined one. This surprises people constantly:
void log(const std::string& s);
void log(bool b);
log("oops"); // calls log(bool)! const char* -> bool beats -> std::string
const char* to bool is a standard conversion; const char* to std::string needs a constructor, which ranks lower. Adding void log(const char*) fixes it.
What does NOT distinguish overloads
| Difference | Valid overload? |
|---|---|
| Number of parameters | Yes |
| Parameter types | Yes |
| Parameter order | Yes |
T vs T& | No — ambiguous for most calls |
T vs const T (by value) | No — top-level const is ignored |
const T& vs T& | Yes |
T* vs const T* | Yes |
| Return type only | No |
| Default argument values only | No |
| Parameter names | No |
void g(int n);
void g(const int n); // ERROR: same function, const on a copy means nothing
Overloading versus default arguments
Both let one name serve several call shapes. Defaults are shorter; overloads are more flexible.
// Default argument: one function, one body
void connect(const std::string& host, int port = 8080);
// Overloads: two functions, two bodies
void connect(const std::string& host);
void connect(const std::string& host, int port);
Use a default when the extra parameter is genuinely optional and the behaviour is identical. Use overloads when the bodies differ, or when the parameter types differ. Do not combine them so that a defaulted call becomes ambiguous:
void h(int a, int b = 0);
void h(int a);
h(1); // AMBIGUOUS -- both are viable
Hiding: overloads do not cross scopes
A name in an inner scope hides all overloads of that name outside it. This bites hardest with inheritance:
struct Base {
void speak(int n);
void speak(const std::string& s);
};
struct Derived : Base {
void speak(double d); // hides BOTH Base::speak overloads
};
Derived d;
d.speak(42); // calls speak(double)! int -> double conversion
d.speak("hi"); // ERROR: no matching function
The fix is one line: using Base::speak; inside Derived pulls the inherited overloads back into scope.
Overloading versus templates
If several overloads would have identical bodies with only the type changed, that is a template, not an overload set:
int larger(int a, int b);
double larger(double a, double b); // duplicated logic
template <typename T>
T larger(T a, T b) { return (a > b) ? a : b; } // one definition, all types
Keep overloads for genuinely different behaviour, and add a non-template overload only when one type needs special handling — a non-template exact match always wins over a template.
Real World Example: A Receipt Formatter
One idea — "format this thing for the receipt" — expressed as a coherent overload set.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
struct LineItem {
std::string name;
int quantity;
double unitPrice;
};
// --- The overload set: every one answers "render this as receipt text".
// Money. Distinct from a plain double by intent, so it gets its own name...
std::string formatMoney(double pounds) {
std::ostringstream out;
out << std::fixed << std::setprecision(2) << "GBP " << pounds;
return out.str();
}
// 1. A label on its own line.
std::string format(const std::string& label) {
return label + "\n";
}
// 2. Needed explicitly, or "SALE" would silently pick the bool overload below.
std::string format(const char* label) {
return format(std::string(label));
}
// 3. A label with a money amount, padded to 32 columns.
std::string format(const std::string& label, double amount) {
const std::string right = formatMoney(amount);
const std::size_t pad = (label.size() + right.size() < 32)
? 32 - label.size() - right.size() : 1;
return label + std::string(pad, '.') + right + "\n";
}
// 4. A full line item -- different parameter TYPE, so a real overload.
std::string format(const LineItem& item) {
std::ostringstream left;
left << item.quantity << " x " << item.name;
return format(left.str(), item.quantity * item.unitPrice);
}
// 5. A whole basket. Same idea, container argument.
std::string format(const std::vector<LineItem>& items) {
std::string out;
for (const LineItem& item : items) { out += format(item); }
return out;
}
// 6. A flag, printed as a word rather than 1/0.
std::string format(bool paid) {
return std::string("Paid: ") + (paid ? "yes" : "no") + "\n";
}
int main() {
const std::vector<LineItem> basket{
{"Coffee beans", 2, 7.50},
{"Filter papers", 1, 2.25},
{"Mug", 3, 4.00}
};
double subtotal = 0.0;
for (const LineItem& item : basket) {
subtotal += item.quantity * item.unitPrice;
}
const double vat = subtotal * 0.20;
std::cout << format("THE CORNER CAFE") // overload 2 -> 1
<< format(basket) // overload 5 -> 4 -> 3
<< format("Subtotal", subtotal) // overload 3
<< format("VAT at 20%", vat) // overload 3
<< format("TOTAL", subtotal + vat) // overload 3
<< format(true); // overload 6
return 0;
}
The set holds together because every overload answers the same question, and each one earns its place by parameter type, not by a slightly different job. Overload 4 does not reimplement column padding — it builds its left-hand text and delegates to overload 3, so the 32-column layout is defined exactly once; overload 5 likewise delegates to 4. That delegation chain is what keeps an overload set from decaying into copy-pasted variants. Overload 2, format(const char*), exists purely to defeat the bool trap: without it, format("THE CORNER CAFE") would convert the string literal to bool — a standard conversion — in preference to constructing a std::string, and the receipt would open with "Paid: yes". formatMoney is deliberately not part of the set: it takes a double and so would collide head-on with any future format(double), and a bare number has no receipt meaning without a label anyway, so a distinct name is honest. Note too that there is no format(int); if one were added, format(true) would break, because bool to int and the exact bool match would no longer be the obvious ranking to a reader even though the compiler still prefers the exact match. Overload sets are easiest to keep correct when they stay small and their parameter types stay far apart.
Common Mistakes
- Overloading on return type.
int f(); double f();does not compile — the call site carries no information the compiler could use. - Overloading on top-level
constof a by-value parameter.void f(int)andvoid f(const int)are the same function. - The bool trap. A
const char*argument prefers aboolparameter over astd::stringone. Add aconst char*overload. - Mixing default arguments with overloads so that some calls match both. The result is an ambiguity error, often in a header someone else includes.
- Overloading
TagainstT&.void f(int)andvoid f(int&)makef(x)ambiguous for a non-constint x. - Assuming a derived class inherits overloads it also redeclares. One same-named member hides the entire base set; add
using Base::name;. - Different behaviour behind the same name.
process(int id)that saves andprocess(const std::string& csv)that deletes is not an overload set, it is a trap. - Copy-pasting one body per type. If only the type varies, write a template.
Best Practices
- Overload only when the functions do the same thing to different inputs. Different behaviour deserves a different name.
- Keep overload sets small and their parameter types far apart.
intversusstd::stringis clear;intversuslongversusdoubleinvites ambiguity. - Add a
const char*overload whenever you have aboolone in the same set. - Have the specific overloads delegate to the general one, so shared logic exists in a single body.
- Prefer a default argument when the parameter is genuinely optional and the behaviour is unchanged.
- Prefer a template when only the type varies; add a non-template overload for the one type that needs special handling.
- In a derived class, write
using Base::method;before adding your own overload. - Read the compiler's candidate list. On an ambiguity error GCC and Clang print every viable overload and why each was rejected — the answer is almost always in that output.
Practice Exercises
- Build the set: Write three
describeoverloads — forint,doubleandconst std::string&— and call each. Then calldescribe('x')anddescribe(10L), predict which overload wins before compiling, and record whether you were right. - Spring the bool trap: Declare
void notify(const std::string&)andvoid notify(bool), then callnotify("urgent"). Confirm which one runs, fix it with aconst char*overload, and confirm the fix. - Make it ambiguous, then repair it: Write
void resize(int width, int height = 100)alongsidevoid resize(int width), callresize(50), and paste the error into a comment. Repair it two ways — once by deleting the default, once by deleting the single-parameter overload — and say which you would ship. - Overload set versus template: Write
clampforintand fordoubleas two overloads, then replace both with one template. Keep a non-templateclamp(bool, bool, bool)overload and verify with a print statement that the non-template version wins forboolarguments.