typestar

Function overloading in C++

One name, three signatures: the compiler picks the right twice from the argument type alone.

#include <string>

// One name, three signatures: the compiler picks by argument type.
int twice(int n) { return n * 2; }
double twice(double x) { return x * 2.0; }
std::string twice(const std::string& s) { return s + s; }

int overload_demo() {
    int a = twice(21);
    double b = twice(1.5);
    std::string c = twice(std::string("echo"));
    return a + static_cast<int>(b) + static_cast<int>(c.size());
}

How it works

  1. Three twice functions share a name but differ in parameter type: int, double, and std::string.
  2. twice(21) binds to the int version and twice(1.5) to the double one, with no casts or renames.
  3. The std::string overload concatenates instead of multiplying; static_cast folds the results into one int.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
394
Tokens
115
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 92 seconds.

Type this snippet

Step 1 of 3 in Functions & lambdas, step 10 of 27 in Language basics.

← Previous Next →