skip to content

Overload Ranking

The compiler ranks every viable overload by conversion and picks one, or reports an ambiguity. Interviewers ask why f(0) calls the int overload and what a default argument changes.

on this pageshow

explore

questions

6

Given C++ overloads print(int), print(long), print(double) and print(const char*), which one does print('A') call, and why?

level: juniorimportance: must knowfreq 70%

answer

  1. three ranks for each argument
  2. exact, promotion, conversion
  3. char goes up to int
  4. wider is not closer

basics

~20 s

print('A') calls print(int). The compiler ranks each argument's conversion as exact match, promotion or conversion; char to int is an integral promotion, while char to long and char to double are conversions, so print(int) wins.

solid answer

~40 s

Overload resolution ranks the implicit conversion each argument needs. There are three ranks for standard conversions: **Exact Match** (no conversion, or only lvalue-to-rvalue, array-to-pointer, function-to-pointer or a qualification adjustment), **Promotion** (integral promotions such as `char`, `short` or `bool` to `int`, and `float` to `double`), and **Conversion** (every other integral, floating, floating-integral, pointer or boolean conversion). `'A'` has type `char`; `char` to `int` is a promotion, while `char` to `long` and `char` to `double` are both conversions, so `print(int)` is the single best viable function. The same table explains the neighbours: `print(3.0f)` picks `print(double)` by floating-point promotion, `print(5L)` is an exact match for `print(long)`, and `print("hi")` reaches `print(const char*)` by array-to-pointer decay, which still counts as an exact match.

code

cpp · 17 lines
cpp
#include <cstdio>

void print(int)         { std::puts("print(int)"); }
void print(long)        { std::puts("print(long)"); }
void print(double)      { std::puts("print(double)"); }
void print(const char*) { std::puts("print(const char*)"); }

int main() {
    print('A');     // char -> int: integral promotion        -> print(int)
    print(3.0f);    // float -> double: floating-point promotion -> print(double)
    print(5L);      // long -> long: exact match               -> print(long)
    print(true);    // bool -> int: integral promotion         -> print(int)
    short s = 2;
    print(s);       // short -> int: integral promotion        -> print(int)
    print("hi");    // array-to-pointer: exact match           -> print(const char*)
    print(0);       // int -> int: exact match                 -> print(int)
}

go deeper

for a junior

Recall the three ranks in order, exact match, promotion, conversion, and that char, short and bool promote to int while float promotes to double.

for a middle

Explain why promotion is a closed list, why char to long is an ordinary conversion, and how array-to-pointer decay still counts as an exact match.

for a senior

Show you can predict a call across a whole overload set, spot the tie that makes it ambiguous, and fix it with an exact overload rather than a cast at every call site.

for a principal

Weigh how many numeric overloads a public API should expose, since each one changes which promotions and conversions callers silently get.

## What the compiler does with an overloaded call When several functions share a name in the same scope, a call to that name goes through **overload resolution**, which runs in three steps: 1. **Candidate functions**: name lookup collects every function called `print` that is visible at the call. 2. **Viable functions**: a candidate survives only if it accepts that number of arguments and each argument has *some* implicit conversion sequence to the matching parameter type. 3. **Best viable function**: the compiler compares the conversion sequences argument by argument and picks the one function that is at least as good everywhere and strictly better somewhere. If no single function wins, the call is **ambiguous** and the program is ill-formed. For `print('A')` all four overloads are candidates. `print(const char*)` is not viable, because no implicit conversion turns a `char` into a pointer. The other three are viable, so the decision comes down to how good each conversion is. ## The three ranks of a standard conversion The standard groups every standard conversion into a category and gives each category a **rank**: | Rank | What belongs to it | Examples | |---|---|---| | **Exact Match** | no conversion; lvalue-to-rvalue; array-to-pointer; function-to-pointer; qualification adjustments | `long` to `long`, `"hi"` to `const char*`, `int*` to `const int*` | | **Promotion** | integral promotions; floating-point promotion | `char`, `short`, `bool` to `int`; `float` to `double` | | **Conversion** | integral, floating-point, floating-integral, pointer, pointer-to-member and boolean conversions | `char` to `long`, `int` to `double`, `double` to `float`, `int*` to `bool` | An Exact Match beats a Promotion, which beats a Conversion. The key detail is that **promotion is a short, closed list**: an integral promotion lifts a small integer type (`char`, `signed char`, `unsigned char`, `short`, `unsigned short`) or `bool` to `int` (or `unsigned int` when `int` cannot hold all the values); the character types `char8_t`, `char16_t`, `char32_t` and `wchar_t`, and unscoped enumerations, promote to the first type from `int` upward that can hold their values; and the only floating-point promotion is `float` to `double`. Everything else is a plain Conversion, however natural it looks. ## Walking through the print calls Applied to the four overloads, the table gives these results: - `print('A')`: `char` to `int` is a promotion; `char` to `long` and `char` to `double` are conversions. **`print(int)` wins.** - `print(3.0f)`: `float` to `double` is the floating-point promotion; `float` to `int` and `float` to `long` are floating-integral conversions. **`print(double)` wins.** - `print(5L)`: an exact match for `print(long)`. - `print(true)` and `print(short_value)`: both promote to `int`. - `print("hi")`: the literal has type `const char[3]`; decaying it to `const char*` is an array-to-pointer conversion, which is an **Exact Match** rank transformation. - `print(0)`: an exact match for `print(int)`. The literal `0` is also a null pointer constant, so `print(const char*)` is viable too, but only through a pointer conversion, which ranks lower. ## Wider is not closer The most common wrong intuition is that `char` "fits best" in the next wider integer type, or that `long` is "closer" to `char` than `double` is. The standard has no notion of distance between types. `char` to `long` and `char` to `double` are both Conversion rank, so if `print(int)` were removed, `print('A')` with only `print(long)` and `print(double)` would be **ambiguous**, not a call to `print(long)`. The same is true in reverse: `double` to `float` is a Conversion, not a promotion, so a `float` overload does not attract `double` arguments. Two more refinements matter in everyday code: - If an exact overload exists, it always wins: adding `print(char)` would make `print('A')` call it. - A standard conversion sequence of any rank beats a **user-defined conversion** (a converting constructor or a conversion operator), and both beat matching a C-style `...` parameter. ## Enumerations follow the same table Enumerations are a frequent follow-up: - An **unscoped enumeration** without a fixed underlying type promotes to `int` (or the first integer type that can hold its values), so with `enum Level { Low, High };` the call `print(High)` picks `print(int)` by integral promotion. - A **scoped enumeration** (`enum class`) has no implicit conversion to any arithmetic type, so `print(Mode::Fast)` finds no viable function at all and fails with `no matching function for call to 'print'`. ## Reading the result in code The snippet in the code example compiles cleanly and prints one line per call, so it is a quick way to check an intuition before an interview. When the ranking cannot decide, the compiler says so: clang reports `call to 'print' is ambiguous` and lists the tied candidates, which is the signal to add an exact overload or to cast the argument at the call site.

  • With only print(long) and print(double) declared, what does print('A') do?
    It is ambiguous. `char` to `long` is an integral conversion and `char` to `double` is a floating-integral conversion; both have Conversion rank, and the standard has no tie-breaker based on which type is wider or "closer". The compiler rejects the call and lists both candidates.
  • Why does print("hi") count as an exact match when the argument is an array?
    A string literal has type `const char[3]`. Turning an array into a pointer to its first element is an array-to-pointer conversion, which the standard classifies as an lvalue transformation with **Exact Match** rank. So `print(const char*)` needs nothing that ranks below exact.
  • Which rank does double to float have, and why does it matter?
    It is a floating-point **conversion**, not a promotion; only `float` to `double` is a promotion. So with `print(float)` and `print(int)`, a call `print(1.5)` is ambiguous, because both need a Conversion-rank step.

A courier with parcels for three addresses picks the door whose label needs no relabelling, then one needing a standard sticker, and only then one needing a full rewrite; two doors both needing a rewrite is a dispute, not a choice.

  • char to long is preferred because long is the closer wider integer type
  • Any integer argument matches every integer overload equally well
  • float to double is an ordinary conversion, just like double to float
  • The compiler picks the first declared overload that accepts the argument
  • A string literal needs a real conversion to reach a const char* parameter
open as a page

In C++, with overloads f(int) and f(char*), what do the calls f(0), f(nullptr) and f(NULL) each resolve to?

level: middleimportance: must knowfreq 65%

basics

~10 s

f(0) calls f(int), an exact match. f(nullptr) calls f(char*), because std::nullptr_t never converts to int. f(NULL) depends on the implementation's NULL: defined as 0 it calls f(int); clang's __null makes the call ambiguous.

open as a page

Why is the C++ call print(42u) ambiguous when only print(int), print(long) and print(double) are declared?

level: middleimportance: should knowfreq 50%

basics

~20 s

42u has type unsigned int, which promotes to nothing. Reaching int, long or double is a Conversion-rank step in every case, and equal ranks do not compare, so no overload is better and the call is ambiguous.

open as a page

In C++, why does print(3.14) become ambiguous after you add print(double, int precision = 2) beside print(double)?

level: middleimportance: should knowfreq 45%

basics

~20 s

A default argument only lets the call omit a trailing argument; the compiler fills it in at the call site. With one argument both overloads are viable with the same exact match, so neither wins and the call is ambiguous.

open as a page

A C++ library declares print(bool) and print(const std::string&); why does print("hello") print true, and how do you block it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The literal reaches bool through standard conversions (array-to-pointer, then pointer-to-bool), while std::string needs a user-defined conversion, and any standard conversion sequence beats a user-defined one. Add an exact print(const char*) overload, or declare it = delete.

open as a page

Why would a C++ class overload a getter as text() const& and text() &&, and which one does make().text() call?

level: seniorimportance: should knowfreq 35%

basics

~20 s

make() returns a temporary, so make().text() calls text() &&, while lvalues use text() const&. The && overload can move the member out and return it by value, so binding its result to a reference no longer dangles.

open as a page