Ch6.6: Default Arguments

Overview

C++ allows function parameters to have default values. When a caller omits an argument, the default value is used instead.

In this chapter, you will learn:

1. Basic default arguments

A default argument is specified using = value in the parameter list.


void scale(int x, int factor = 2)
{
    ::fast_io::println(x * factor);
}

int main()
{
    scale(10);     // uses default factor = 2
    scale(10, 5);  // uses factor = 5
}

Default arguments work best with built‑in types because they are cheap and unambiguous.

2. Default arguments belong in declarations

Default arguments should appear in the function declaration, not the definition. This avoids multiple-definition problems and keeps headers self‑contained.


// header (math.hpp)
int power(int base, int exp = 2);

// source file (math.cpp)
int power(int base, int exp)
{
    int result{1};
    for(int i{}; i < exp; ++i)
        result *= base;
    return result;
}

If you put defaults in both places, the compiler will reject the code.

3. Ordering rules for default arguments

Once a parameter has a default value, all parameters to its right must also have defaults.


void f(int x = 0, int y = 0);   // ✔ OK
void g(int x = 0, int y);       // ❌ error — y has no default

This rule ensures that calls remain unambiguous.

4. Interaction with function overloading

Default arguments and overloading can interact in surprising ways.


void h(int x, int y = 0);
void h(int x);

A call like h(5) is ambiguous:

Avoid mixing overloads and default arguments unless the design is very clear.

5. When default arguments are evaluated

Default arguments are evaluated at the call site, not at the function definition.


int next_id()
{
    static int counter{};
    return ++counter;
}

void assign_id(int id = next_id());

int main()
{
    assign_id();  // id = 1
    assign_id();  // id = 2
}

Each call evaluates the default expression again.

Key takeaways