AnyCompiler

Functions and Overloading

C++ lets you declare multiple functions with the same name as long as their parameter types differ — this is function overloading. The compiler picks the right one at compile time based on the argument types at the call site, with no runtime cost or dispatch involved.

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

int main() {
    cout << add(3, 4) << endl;
    cout << add(3.5, 2.5) << endl;
    return 0;
}
Output
7
6

Default arguments

A parameter can have a default value, used whenever the caller omits that argument. It's a simpler alternative to overloading when the only thing that changes between versions of a function is one trailing value.

#include <iostream>
using namespace std;

int multiply(int a, int b = 2) {
    return a * b;
}

int main() {
    cout << multiply(5) << endl;
    cout << multiply(5, 3) << endl;
    return 0;
}
Output
10
15

What a real overload-resolution error looks like

Overload resolution only works when the compiler can match the call to exactly one candidate through its normal conversion rules — it won't silently coerce an argument through a conversion that isn't implicit and unambiguous. This is genuinely what g++ reports when no overload matches — captured from a real run, not written to look plausible:

#include <iostream>
using namespace std;

void greet(int id) {
    cout << "id: " << id << endl;
}

void greet(double score) {
    cout << "score: " << score << endl;
}

int main() {
    greet("hello");
    return 0;
}
Output
main.cpp: In function ‘int main()’:
main.cpp:13:11: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
   13 |     greet("hello");
      |           ^~~~~~~
      |           |
      |           const char*
main.cpp:4:16: note:   initializing argument 1 of ‘void greet(int)’
    4 | void greet(int id) {
      |            ~~~~^~

A string literal can't silently become an int or a double, so neither overload matches, and the whole program fails to compile rather than picking a surprising candidate.

Next: control flow — if/else, for, while, and switch.

Practice exercise

Write two overloads of square: one for int, one for double. Call square(6) and print the result.