Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 171 ยท Functions

Function Overloading

Learn C++ function overloading - which signatures can overload, how the compiler ranks candidates, why calls become ambiguous, and when to use templates instead.

In C, every function needs a unique name, so libraries end up with families like abs, labs, fabs and llabs that all do the same thing for different types. C++ lets several functions share one name as long as their parameter lists differ. This is function overloading, and it's why you can call std::abs on an int, a long or a double and always get the right version.

Overloading makes interfaces feel natural: print(42), print("hi") and print(point) all read the same way. But it's also one of the more intricate parts of C++, because the compiler has to choose the best match for every call, and its rules sometimes pick something you didn't expect, or refuse to pick at all. In this lesson you'll learn what makes overloads distinct, how overload resolution ranks candidates, how to read and fix "ambiguous" errors, and when a template is the better tool.

Declaring overloads

Two functions with the same name in the same scope are overloads if their parameter lists differ in number or types:

C++ Three overloads of describe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The compiler chooses an overload at compile time, based only on the static types of the arguments. There is no run-time cost: after compilation, each call simply jumps to one specific function. (Choosing at run time based on an object's real type is a different feature: virtual functions, covered in Virtual Functions and Polymorphism.)

Under the hood, the compiler gives each overload a unique mangled name that encodes its parameter types, such as _Z8describei for describe(int) and _Z8described for describe(double) with GCC. That's how the linker tells them apart. You'll see mangled names in linker errors from time to time.

What counts as a different signature

Only the parameter types (and, for member functions, qualifiers like const) distinguish overloads. Several things look different but are not:

Difference Makes a valid overload?
Number of parameters Yes
Parameter types (int vs double) Yes
T& vs const T& Yes
T* vs const T* Yes
Return type only No: error, the call can't tell them apart
Parameter names only No: same function
Top-level const on a by-value parameter (int vs const int) No: same function
A typedef/using alias for the same type No: same type
Default arguments No: not part of the signature

The return-type rule follows from how calls work: in f(3); there's nothing that says which return type you want. And top-level const on a by-value parameter only affects the function's own copy, so callers can't see the difference:

C++
int parse(const std::string& text);
double parse(const std::string& text);   // error: differs only in return type

void set_size(int n);
void set_size(const int n);              // same function, redeclared (not an overload)

using Meters = double;
void walk(double distance);
void walk(Meters distance);              // same function: Meters IS double

That last example disappoints people who hope type aliases add safety. If you want Meters and Seconds to be truly distinct types, wrap them in small structs; aliases (see Type Aliases) are just new names.

How the compiler chooses: overload resolution

For each call, the compiler:

  1. collects every function with that name that is visible (the candidates),
  2. keeps those that could accept the arguments, possibly after conversions (the viable functions),
  3. ranks them by how good each argument's conversion is, and picks the best. If no single function is best, the call is ambiguous and won't compile.

The ranking of conversions, from best to worst:

Rank Examples
Exact match int to int, int to const int&, array to pointer, adding const to a pointer target
Promotion char, short or bool to int; float to double
Conversion int to double, double to int, int to long, long to int, derived pointer to base pointer, anything to bool
User-defined conversion const char* to std::string via its constructor
Ellipsis matching a C-style ... parameter

The details have more layers, but this table explains almost every result you'll see. Here it is in action:

C++ Which overload wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The last line is the classic overloading surprise. A string literal is a const char[5], which decays to const char* (an exact-match adjustment). Turning a pointer into a bool is a standard conversion. Turning it into a std::string requires a user-defined conversion (calling the constructor). Standard beats user-defined, so show(bool) wins.

Fixes: add an overload that takes const char* or, better, take std::string_view, which you'll meet in std::string_view. In modern code, a single std::string_view overload often replaces both const char* and const std::string& versions. You could also write show("text"s) with the std::string_literals suffix to pass a real std::string.

Ambiguous calls

When two viable functions are equally good, the compiler refuses to guess:

C++
void scale(long value);
void scale(double value);

scale(10);   // error: call of overloaded 'scale(int)' is ambiguous

int to long and int to double are both plain conversions (rank 3), so neither is better. Promotions only go to int and double, not to long. Common sources of ambiguity:

  • Numeric types without an exact overload, like the example above. Add an int overload, or make the caller's type explicit: scale(10L) or scale(10.0).
  • Several parameters pulling in opposite directions. With f(int, double) and f(double, int), the call f(1, 2) is better for the first argument in one and for the second in the other, so neither wins.
  • A default argument that duplicates an overload. void log(std::string_view msg, int level = 0); plus void log(std::string_view msg); makes log("x") ambiguous. (See Default Arguments.)
  • 0 and NULL with pointer and integer overloads. f(int) and f(char*) called with NULL may pick the integer version or be ambiguous. Always use nullptr, whose type std::nullptr_t converts only to pointers.
C++ Fixing an ambiguity and the nullptr rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Overloading on references and const

You can overload a function on whether it receives a modifiable object or a read-only one. The compiler prefers the overload that adds the least qualification:

C++ const and non-const overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Without the std::string&& overload, the temporary would bind to const std::string&; it can never bind to plain std::string&. The && overload is the foundation of move semantics; for now it's enough to know that an rvalue reference parameter matches temporaries best. The same const overloading appears on member functions, where it lets operator[] return a modifiable element on a normal object and a read-only one on a const object (see const Member Functions).

Overloads and scope

Overload resolution only considers functions found by name lookup, and lookup stops at the first scope that has the name. A function declared in an inner scope hides every overload from outer scopes, rather than joining them:

C++
void report(double value);

namespace audit {
    void report(const char* message);

    void run() {
        report(3.5);   // error: only audit::report is found, and 3.5 can't become const char*
    }
}

The same hiding happens when a derived class declares a member function with the name of a base class member. Bring the outer overloads in with a using declaration (using ::report;) when you want them to be considered together. You'll see more of this in Namespaces and Inheritance. Functions can also be found through their arguments' namespaces (argument-dependent lookup), which is why std::println overloads for your own types can live next to those types.

Overloading vs templates

If several overloads have identical bodies and differ only in type, you're writing a template by hand:

C++
int    largest(int a, int b)       { return a > b ? a : b; }
double largest(double a, double b) { return a > b ? a : b; }
long   largest(long a, long b)     { return a > b ? a : b; }

A function template writes the body once and lets the compiler generate a version for each type (see Function Templates):

C++ One template instead of many overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Templates and ordinary functions can overload each other. When a non-template function is an equally good match, the compiler prefers it over a template specialization, which makes overloads a clean way to handle special cases.

A good rule of thumb:

  • Same logic, different types โ†’ one template (or an auto parameter, C++20).
  • Different logic for different types โ†’ overloads.
  • Different meaning โ†’ different names. draw(shape) and draw(card_from_deck) share a word but not a meaning; render and draw_card would be clearer.

Keep every overload in a set doing "the same thing" from the caller's point of view. If a reader has to check which overload runs to understand a call, the overload set is too clever.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pair of declarations is a valid overload?

    References to const and non-const are different parameter types. Return types, parameter names and top-level const on by-value parameters don't distinguish overloads.
  2. 2. With void show(bool) and void show(const std::string&), what does show("hello") call?

    The literal decays to const char*. Converting a pointer to bool is a standard conversion, which ranks above calling std::string's constructor.
  3. 3. With only void f(long) and void f(double), what happens with f(5)?

    int to long and int to double are both ordinary conversions of the same rank, so neither overload is better.
  4. 4. With void g(int) and void g(double), which overload does g('x') call?

    char to int is a promotion, which ranks above the char to double conversion, so g(int) wins.

Summary

  • Functions with the same name and different parameter lists are overloads; the compiler picks one at compile time.
  • Return types, parameter names, top-level const on by-value parameters, aliases and default arguments don't create overloads.
  • Overload resolution ranks conversions: exact match > promotion > standard conversion > user-defined > ellipsis.
  • Watch the classic surprise: a string literal prefers a bool overload over std::string; use std::string_view or a const char* overload.
  • Ambiguous calls happen when two candidates rank equally; fix them with an exact overload or an explicit type, and always pass nullptr for null pointers.
  • Inner-scope declarations hide outer overloads.
  • Same logic for many types โ†’ a template; different logic โ†’ overloads; different meaning โ†’ different names.

Next: inline Functions, where you'll learn what inline really means in modern C++ (hint: it's not mainly about speed).