C++ Default Arguments: Syntax, Rules, and Examples

C++ Default Arguments: Syntax, Rules, and Examples


C++ default arguments let you assign a value to a function parameter so callers can skip passing it. They’re perfect for writing cleaner, beginner-friendly functions without creating many overloads. In this step by step guide to C++ default arguments with examples, you’ll learn what they are, why they’re useful, the rules you must follow, and how to use them correctly with simple, runnable code. This tutorial is aimed at students, beginners, and anyone learning C++ in school or college. If you’re new to C++, consider visiting our main C++ tutorials page at CodDesire C++ as well.

What are C++ default arguments?

C++ default arguments with examples: diagram filling missing function parameters with default values during a call
How C++ default arguments auto-fill omitted parameters at call time

Default arguments (also called default parameters) are values you attach to function parameters. When you call the function, you can omit those parameters, and the compiler will substitute the defaults for you. This keeps your calls short and readable while still allowing customization when needed. In short, default parameters in C++ for beginners make functions flexible without repeating similar code.

Syntax and rules

C++ default arguments with examples: RGB color function where a default alpha parameter is applied when not provided
Practical example: defaults for optional parameters like alpha in a color function

Here’s the basic syntax:

Code
return_type function_name(type1 param1 = default1, type2 param2 = default2, ...);
  • Trailing-only rule: Once you give a parameter a default value, all parameters to its right must also have defaults.
  • Declare defaults once: Provide the default value on a single declaration (typically in a header). Don’t repeat it in another declaration or in the function definition.
  • Evaluation: The default expression is evaluated at the call site each time you omit the argument.
  • General expressions allowed: Defaults can be expressions, not just constants (as long as they’re valid and accessible at the point of declaration).

Example 1: Greeting function with default parameters

This simple example shows how to use default arguments to print a greeting. We’ll default the name to “Student” and the number of repeats to 1.

Code
#class="cd-package">include <iostream>
#class="cd-package">include <string>

void greet(const std::string& name = "Student", int times = 1) {
    for (int i = 0; i < times; ++i) {
        std::cout << "Hello, " << name << "!" << std::endl;
    }
}

int main() {
    greet();                 // uses both defaults
    std::cout << "----" << std::endl;
    greet("Aman");           // uses default times = 1
    std::cout << "----" << std::endl;
    greet("Priya", 3);       // overrides both
}
Output
Hello, Student!
----
Hello, Aman!
----
Hello, Priya!
Hello, Priya!
Hello, Priya!

Example 2: Area with a default width

Here’s a practical example for school and college programming learners. We’ll compute the area of a rectangle and default the width to 10.

Code
#class="cd-package">include <iostream>

int area(int length, int width = 10) {
    return length * width;
}

int main() {
    std::cout << "Area (7 x default 10): " << area(7) << std::endl;
    std::cout << "Area (7 x 2): " << area(7, 2) << std::endl;
}
Output
Area (7 x default 10): 70
Area (7 x 2): 14

Example 3: Defaults are evaluated at each call

An important rule in this C++ default arguments tutorial: default arguments are evaluated at the call site, every time you omit them. The example below uses a function to generate a new ID on every call where the argument is missing.

Code
#class="cd-package">include <iostream>

int nextId() {
    static int id = 100;
    return ++id;
}

void logEvent(int id = nextId()) {
    std::cout << "Logging event with id: " << id << std::endl;
}

int main() {
    logEvent();      // uses nextId() -> 101
    logEvent();      // uses nextId() -> 102
    logEvent(999);   // explicit argument
    logEvent();      // uses nextId() -> 103
}
Output
Logging event with id: 101
Logging event with id: 102
Logging event with id: 999
Logging event with id: 103
How a default argument is applied (call-site evaluation)
Step 1
Declare
void logEvent(int id = nextId());

Step 2
Call
logEvent(); // id omitted

Step 3
Substitute default
Compiler inserts id = nextId() at the call site.

Step 4
Evaluate
The default expression runs now, producing a fresh ID each time.

Step 5
Execute
Function runs with the computed argument value.

Tip: Because evaluation happens at the call site, default expressions can yield different results across calls.

Where to put default parameter values (header vs source)

You should normally place default arguments on a function’s declaration where users can see it—typically in a header (.hpp/.h) file—and avoid repeating it in the definition (.cpp). Declaring the default once prevents redefinition errors. Here’s a single-file illustration:

Code
#class="cd-package">include <iostream>

// Declaration with default (think: header)
void show(int x = 10);

// Definition without repeating the default (think: source)
void show(int x) {
    std::cout << "x = " << x << std::endl;
}

int main() {
    show();     // uses default x = 10
    show(50);   // overrides default
}
Output
x = 10
x = 50

Common mistakes with default arguments in C++ and how to fix them

  • Putting a default in the middle of the parameter list
    After the first defaulted parameter, all following parameters must also have defaults.
Code
// Wrong: default in the middle
void bad(int a = 1, int b); // Error: non-default parameter ___CDPHSTR0___ follows default parameter
Code
// Correct: make trailing parameters defaulted too
void good(int a = 1, int b = 2);
  • Redefining the same default argument in multiple declarations
    Provide the default once. Don’t repeat it elsewhere.
Code
void f(int x = 1);
// void f(int x = 2); // Error: redefinition of default argument
void f(int x);       // OK: no second default
  • Using earlier parameters in later defaults
    You can’t use function parameter names in default arguments (except in certain unevaluated contexts). This common beginner error won’t compile.
Code
// Won___CDPHSTR0___a' is not allowed in default argument expression here

// Use an overload or reorder parameters (if it makes sense), for example:
int sum(int a, int b);               // no default here
int sum_with_default_b(int a) {      // helper with default logic
    return sum(a, a + 1);
}
  • Expecting virtual dispatch to choose defaults
    Default arguments are selected based on the static type at the call site, not the dynamic type. This can surprise you with virtual functions.
Code
#class="cd-package">include <iostream>

struct Base {
    virtual void hello(int n = 1) {
        std::cout << "Base/Derived::hello, n = " << n << std::endl;
    }
};

struct Derived : Base {
    void hello(int n = 2) override {
        std::cout << "Base/Derived::hello, n = " << n << std::endl;
    }
};

int main() {
    Derived d;
    Base* pb = &d;

    d.hello();    // default picked from Derived (static type is Derived) -> n = 2
    pb->hello();  // virtual call chooses Derived::hello, but default comes from Base -> n = 1
}
Output
Base/Derived::hello, n = 2
Base/Derived::hello, n = 1

Guideline: avoid giving different defaults in overrides. Prefer a single default in the base or avoid defaults with virtuals.

C++ default arguments vs function overloading explained

Both features help you offer flexible calls. Use default arguments when differences are only “which values are passed.” Use overloading when parameter types differ or you need very different behavior.

Aspect
Default arguments
Function overloading

Best for
Same function behavior with optional values
Different parameter types or significantly different logic

Number of functions
One function with optional parameters
Multiple functions (same name, different signatures)

Call site readability
Short, clear calls; omitted args are obvious
Explicit overload selection by argument types

Good when
Only values vary (e.g., width = 80, height = 25)
Types or semantics vary (e.g., draw(int), draw(double))

Lambdas with default parameters (C++14+)

You can use default parameters in lambda expressions too (C++14 and later). This is great for small helpers.

Code
#class="cd-package">include <iostream>

int main() {
    auto multiply = [](int x, int factor = 2) { return x * factor; };

    std::cout << multiply(10) << std::endl;     // uses default factor = 2
    std::cout << multiply(10, 3) << std::endl;  // overrides default
}
Output
20
30

How to use default arguments in C++ effectively

Practical checklist: Using C++ default arguments effectively
  • Give defaults only to trailing parameters.
  • Declare each default once (typically in a header); do not repeat it in the definition.
  • Remember call-site evaluation: defaults run every time you omit the argument.
  • Avoid using parameter names inside other parameters’ default expressions.
  • Be cautious with virtual functions—defaults are chosen by static type; keep one authoritative default.
  • Prefer overloading or templates when argument types or behavior differ notably.
  • Document the meaning of each default so callers understand the intent.

FAQ: C++ default arguments with examples

What are default arguments in C++ and how do they work?

They are values attached to function parameters so you can omit those arguments in calls. The compiler fills them in. They’re looked up when declared and evaluated each time you call the function without passing that parameter.

How do I declare a function with default parameters in C++?

Add the default after the parameter in the declaration, for example: void draw(int width = 80, int height = 25);. Don’t repeat the defaults in the definition.

Can I place a default argument in the middle of a parameter list in C++?

No. After the first parameter with a default, all following parameters must also have defaults.

What is the difference between default arguments and function overloading in C++?

Default arguments keep one function and let you skip values. Overloading creates multiple functions with the same name but different parameter lists or types. Choose defaults when only values change; choose overloading when types or logic differ.

Where should I put default parameter values in C++—in the header or source file?

Put them in the function declaration that other code includes (typically the header). In the source file’s definition, do not repeat the defaults.

Practice: Try it yourself

  1. Write a function print_line that prints a character repeated N times, with defaults ch = '-' and count = 10.
  2. Create scale(int value, int by = 2) and call it with and without the second argument.
  3. Experiment with the call-site evaluation rule: default to a function that returns a changing value and observe the outputs.

Summary

Default parameters in functions with simple examples are one of the easiest ways to write cleaner, shorter C++ code. Remember: keep defaults on trailing parameters, declare them once (usually in headers), and know that defaults are evaluated at the call site. For more beginner-friendly C++ lessons, visit our main C++ page: CodDesire C++ Tutorials.

Sources / Further reading

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted