01 / 21

Default Arguments
in C++

Learn how to simplify function calls by assigning fallback values to parameters, making your code cleaner and more flexible.

Programming C++

What Are Default Arguments?

A default argument is a value assigned to a function parameter in the function declaration. If the caller does not provide a value for that parameter, the compiler automatically uses the default.

void greet(string name = "World");

greet("Alice");  // prints "Hello, Alice"
greet();          // prints "Hello, World"

Why Use Default Arguments?

✓ Fewer Overloads
One function can handle multiple calling styles instead of writing many overloaded versions.
✓ Cleaner Calls
Callers only specify what they need to change, skipping common values.
✓ Backward Compatible
Adding a new parameter with a default won't break existing code that already calls the function.

How the Compiler Fills the Gap

void display(string msg, int count = 1, bool caps = false)
display("Hi")
"Hi", 1, false
display("Hi", 3)
"Hi", 3, false
display("Hi", 3, true)
"Hi", 3, true
What you write What the compiler sees

The Core Rule: Right-to-Left

Default arguments must be assigned from the rightmost parameter toward the left, with no gaps. Once a parameter has a default, every parameter to its right must also have one.

// VALID: defaults fill from right
void draw(int x, int y, int w = 100, int h = 100);

// INVALID: gap in defaults
void draw(int x, int y = 0, int w, int h = 100);  // ERROR!

Declaration vs Definition

In C++, default values are typically specified in the function declaration (the prototype), not in the definition. Specifying them in both is a compiler error.

// header.h (declaration) — defaults go here
void log(string msg, int level = 1);

// source.cpp (definition) — NO defaults here
void log(string msg, int level) {
    // implementation...
}

Defaults vs Function Overloading

Default Arguments Overloading
Functions needed 1 Multiple
Different logic per variant? No: same body Yes: each has its own body
Parameter types can differ? No Yes
Best when Same logic, fewer args Different behavior needed

How to Apply Default Arguments

1
Identify optional parameters: Which parameters have a sensible "usual" value most callers would use?
2
Order parameters: Place required parameters on the left and optional ones on the right.
3
Assign defaults right-to-left: Every parameter to the right of the first default must also have a default.
4
Place defaults in the declaration: Put them in the header/prototype, not in the function body.
5
Test with varied calls: Call with all arguments, some omitted, and only required ones.

Example 1: Power Function

Write a function that raises a base to an exponent, defaulting to squaring.

double power(double base, int exp = 2) {
    double result = 1;
    for (int i = 0; i < exp; i++)
        result *= base;
    return result;
}

cout << power(5);      // 25  (5^2, default exp)
cout << power(5, 3);   // 125 (5^3, exp overridden)

Example 2: Print Separator

A utility that prints a separator line with configurable character, length, and newlines.

void separator(char ch = '-', int len = 40, bool newline = true) {
    for (int i = 0; i < len; i++)
        cout << ch;
    if (newline) cout << '\n';
}

separator();             // ----...---- (40 dashes + newline)
separator('=');          // ====...==== (40 equals + newline)
separator('*', 20);     // **...** (20 stars + newline)
separator('*', 20, false); // **...** (20 stars, no newline)

Example 3: Grade Calculator

string letterGrade(double score,
                     double aThresh  = 90.0,
                     double bThresh  = 80.0,
                     double cThresh  = 70.0) {
    if (score >= aThresh) return "A";
    if (score >= bThresh) return "B";
    if (score >= cThresh) return "C";
    return "F";
}

cout << letterGrade(85);          // "B" (standard scale)
cout << letterGrade(85, 85.0);     // "A" (curved: A at 85+)

You Cannot Skip Middle Arguments

Unlike some other languages, C++ does not allow you to skip a defaulted parameter and supply a later one. Arguments are always matched left to right.

void setup(int width = 800, int height = 600, bool fullscreen = false);

// Want fullscreen but keep default width & height?
setup(true);           // WRONG! true converts to int 1 (width=1)
setup(800, 600, true); // CORRECT: must supply all preceding args

Defaults Are Resolved at Compile Time

Compile-Time Substitution
The compiler inserts the default value at the call site. No runtime overhead: it's as fast as passing the value explicitly.
Visibility Matters
The compiler must see the declaration with the defaults before the call. That's why defaults belong in header files.

Defaults Can Be Expressions

Default values are not limited to literals. They can be variables, function calls, or complex expressions: anything that can be evaluated at the call site.

int screenWidth = 1920;

void resize(int w = screenWidth,
            int h = screenWidth * 9 / 16) {
    // w defaults to 1920, h defaults to 1080
}

// If screenWidth changes before the call,
// the new value is used!
screenWidth = 2560;
resize();  // w=2560, h=1440

Common Mistakes to Avoid

✕ Defaults in Both Places
Specifying the default in both the declaration and the definition causes a redefinition error.
✕ Gap in Default Chain
Giving a default to a middle parameter but not to those on its right breaks the right-to-left rule.
✕ Skipping Arguments
Trying to omit a middle argument and supply a later one: C++ matches arguments strictly left-to-right.
✕ Ambiguous Overloads
A defaulted function and an overloaded version with fewer parameters can create ambiguity the compiler can't resolve.

Quick Reference Summary

Rule Detail
Placement In the declaration (prototype), not definition
Order Right-to-left: no gaps allowed
Matching Arguments fill left-to-right: can't skip
Value types Literals, constants, variables, expressions
Evaluation At each call site, at compile time
Overload conflict Avoid defaults + overloads with same call signature

Question 1 of 5

Which declaration correctly uses default arguments?

Question 2 of 5

Given: void print(string s, int n = 1, char end = '\n');
What does print("Hi", 3) resolve to?

Question 3 of 5

Where should default argument values be specified when using separate header and source files?

Question 4 of 5

What happens if you define both:
void foo(int a, int b = 5); and void foo(int a);
then call foo(10)?

Question 5 of 5

Given: void draw(int x, int y, int w = 100, int h = 100);
Which call is invalid?