1. Goals
Use one function name for related operations with different parameter lists.
Predict common exact-match, promotion, and conversion choices.
Recognize ambiguity and select an overload when taking a function address.
2. Prerequisites
You know function declarations and definitions, numeric types,
std::string, and const references. You have also passed a comparison
function to std::sort. This lesson covers names that refer to several functions.
3. Explanation
Overloading allows functions in the same scope to share a name when
their parameter lists distinguish them, such as valueKind(int) and
valueKind(double). Different parameter counts or types can define
another overload. Changing a parameter's name cannot.
The example has three valueKind functions accepting int, double,
or const std::string&. Each returns a label identifying the selected
version. Parameters are unnamed because the bodies do not need their
values; parameter types still belong to the declarations and affect selection.
formatLabel(title) and formatLabel(title, category) demonstrate
different argument counts. Both produce book labels. Share a name
between related operations; unrelated tasks deserve separate names
that do not force the reader to guess.
For an ordinary function call, the compiler considers declarations visible at the call, excludes functions that cannot accept the arguments, and looks for the best remaining choice. It does not choose by definition order or try calling each function at runtime. For this lesson's simple cases:
valueKind(3)selectsintthrough an exact type match.valueKind(3.5)selectsdouble; that literal has typedouble.shortpromotes toint, which beats conversion todouble.floatpromotes todouble, which beats conversion toint.A
std::stringselects theconst std::string¶meter.
Promotion is a specific category defined by the language, not every
change to a larger type. Changing int to long is a conversion,
not a promotion. Overload resolution has further rules; you need not
memorize them all now. Recheck existing calls when adding an overload.
valueKind(3L); is an intentionally rejected call. The L suffix
makes a long. Converting long to either int or double has
conversion rank; neither is better here, so the call is ambiguous.
This remains true when long and int have the same size on a
machine: they are distinct types. Use 3 if you actually mean int,
or static_cast<double>(3L) to deliberately select double. Do not
cast merely to silence an error without considering possible data loss.
The conversion ranking rules
underlie these choices.
Two free functions with identical names and parameters cannot be
overloaded solely by return type. For example, int quantity(); and
double quantity(); cannot coexist as overloads in one scope.
Writing double result = quantity(); does not select the function
based on the receiving variable's type. Also, void update(int); and
void update(const int); declare the same function: top-level const
on a by-value parameter creates no overload. In contrast, int& and
const int& are different parameter types, though combinations of
overloads still need care to avoid ambiguity.
The C++17 overloadable declaration rules
describe these restrictions.
When taking an overloaded function's address, its name alone does not
select one function. const char* (*classifyInteger)(int) = valueKind;
declares a pointer to a function accepting int and returning
const char*. That destination type selects valueKind(int).
There is no owning pointer or memory allocation here. The returned
labels point to string literals with lifetime lasting throughout the
program; do not modify or deallocate them.
The next lesson introduces templates: one definition for a family of suitable types. Overloads remain useful for operations that need different implementations; templates do not replace every overload.
After Foundation, explore how templates participate in selection in the C++11 deduction and overload lesson.
4. Runnable example
Compile as C++17. All calls here are unambiguous. Try valueKind(3L);
separately in the practice section.
#include <iostream>
#include <string>
const char* valueKind(int) {
return "int";
}
const char* valueKind(double) {
return "double";
}
const char* valueKind(const std::string&) {
return "string";
}
std::string formatLabel(const std::string& title) {
return "Book: " + title;
}
std::string formatLabel(const std::string& title, const std::string& category) {
return category + ": " + title;
}
int main() {
const short small = 3;
const float fraction = 1.5F;
const std::string title = "C++";
std::cout << "3 -> " << valueKind(3) << '\n';
std::cout << "3.5 -> " << valueKind(3.5) << '\n';
std::cout << "short -> " << valueKind(small) << '\n';
std::cout << "float -> " << valueKind(fraction) << '\n';
std::cout << "title -> " << valueKind(title) << '\n';
std::cout << formatLabel(title) << '\n';
std::cout << formatLabel(title, "Foundation") << '\n';
const char* (*classifyInteger)(int) = valueKind;
std::cout << "Function pointer -> " << classifyInteger(7) << '\n';
std::cout << "Explicit double -> " << valueKind(static_cast<double>(3L)) << '\n';
return 0;
}Output:
3 -> int
3.5 -> double
short -> int
float -> double
title -> string
Book: C++
Foundation: C++
Function pointer -> int
Explicit double -> double5. Common mistakes
Expecting the receiving variable to select an overload by return type.
Treating a renamed parameter or top-level
conston a value parameter as a new overload.Expecting the first declared function to win a tie.
Adding an overload without recompiling existing calls that use conversions.
Confusing free-function overloading with
overridein class inheritance.Casting a large value to
intmerely to resolve ambiguity while ignoring its range.
6. Practice
Predict the selected versions for
int,short,float,double, andstd::stringbefore running the program. Explain why the two promotions select different overloads.Add
valueKind(3L);insidemainon its own. Compilation must fail because the call is ambiguous. Remove it and use the explicit conversion shown in the example; the program must run again.Create a small file declaring
int quantity();anddouble quantity();outsidemain. Compilation must fail before linking. Fix it with separate names or meaningfully different parameter lists.Add
valueKind(long)returning"long", then retry3L: it must choose the new overload. Check that3still selectsint. Restore the original example afterwards to compare its recorded output.
7. Self-check
Why does
valueKind(small)selectintforshort small = 3? Answer:shortpromotes toint. In this example that promotion beats conversion todouble.Why is
valueKind(3L)ambiguous even though3fits both types? Answer: selection follows types and conversion rules, not a runtime value check. Both paths fromlonghave conversion rank and neither is better here.Which function does
classifyIntegerselect, and does it needdelete? Answer: its typeconst char* (*)(int)selectsvalueKind(int). It points to an existing function and owns no allocated storage; never usedeleteon it.
Sample code
Source file
cpp98_foundation/22_overloads/main.cpp
#include <iostream>
#include <string>
const char* valueKind(int) {
return "int";
}
const char* valueKind(double) {
return "double";
}
const char* valueKind(const std::string&) {
return "string";
}
std::string formatLabel(const std::string& title) {
return "Book: " + title;
}
std::string formatLabel(const std::string& title, const std::string& category) {
return category + ": " + title;
}
int main() {
const short small = 3;
const float fraction = 1.5F;
const std::string title = "C++";
std::cout << "3 -> " << valueKind(3) << '\n';
std::cout << "3.5 -> " << valueKind(3.5) << '\n';
std::cout << "short -> " << valueKind(small) << '\n';
std::cout << "float -> " << valueKind(fraction) << '\n';
std::cout << "title -> " << valueKind(title) << '\n';
std::cout << formatLabel(title) << '\n';
std::cout << formatLabel(title, "Foundation") << '\n';
const char* (*classifyInteger)(int) = valueKind;
std::cout << "Function pointer -> " << classifyInteger(7) << '\n';
std::cout << "Explicit double -> " << valueKind(static_cast<double>(3L)) << '\n';
return 0;
}