Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 171 ยท Functions

Default Arguments

Learn C++ default arguments - giving parameters default values, the trailing-defaults rule, where to declare defaults, evaluation rules, and when overloads are better.

Many functions have a parameter that almost every caller sets to the same value. A logging function usually logs at the "info" level. A function that pads text usually pads with spaces. Forcing every caller to spell out the common value adds noise and invites typos. Default arguments let you write that common value once, in the function declaration, so callers can leave it out.

In this lesson you'll learn how to declare default arguments, the rules the compiler enforces (defaults must be trailing, and you may only give them once), where they belong when code is split into headers, how the default expressions are evaluated, and the situations where an overload or a small options struct is the better tool. You should already be comfortable with Functions and Parameters.

Giving a parameter a default value

Write = value after a parameter in the declaration. When a call leaves that argument out, the compiler fills in the default for you:

C++ A greeting with a default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The first call is rewritten by the compiler as greet("Ada", "Hello"). Nothing happens at run time that you couldn't have typed yourself: a default argument is pure convenience at the call site. The function body always receives a value for every parameter and has no way to tell whether the caller wrote it or the default supplied it.

A function can have several defaults:

C++
std::string pad(const std::string& text, std::size_t width = 10, char fill = ' ');

pad("id");            // pad("id", 10, ' ')
pad("id", 6);         // pad("id", 6, ' ')
pad("id", 6, '.');    // all three given

Rule 1: defaults must be trailing

Arguments are matched to parameters strictly left to right. C++ has no named arguments, so there is no way to skip a parameter in the middle. That leads to the main rule: once a parameter has a default, every parameter after it must have one too.

C++
void ok(int a, int b = 2, int c = 3);    // fine
void bad(int a = 1, int b, int c = 3);   // error: b has no default

The same left-to-right matching means you can't keep the default for width while choosing fill. To pass a fill character, you must also pass a width:

C++ Defaults fill in from the right

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This is why the order of parameters matters when you design a function with defaults. Put the parameter callers change most often first among the defaulted ones, and the one they almost never touch last.

Rule 2: give each default only once

A function can be declared many times but defined only once. Default arguments belong to a declaration, and the standard forbids repeating a default for the same parameter in a later declaration in the same scope, even if the value is identical:

C++
void connect(const std::string& host, int port = 443);   // declaration

void connect(const std::string& host, int port = 443) {  // error: default argument given twice
    // ...
}

The fix is to put the default on the declaration and leave it off the definition:

C++
void connect(const std::string& host, int port = 443);   // declaration with default

void connect(const std::string& host, int port) {        // definition without it
    // ...
}

Many programmers add a comment such as int port /* = 443 */ in the definition so readers can see the default without jumping to the declaration.

(Technically, later declarations may add defaults for parameters that don't have one yet, working from the right. This is legal but confusing, and you should never rely on it.)

Where defaults go with header files

When you split a program into a header (.h) and a source file (.cpp), which you'll do in Header Files and Multiple Source Files, the rule above has a clear consequence: defaults go in the header declaration.

C++
// network.h
#pragma once
#include <string>

void connect(const std::string& host, int port = 443, int timeout_ms = 5000);
C++
// network.cpp
#include "network.h"

void connect(const std::string& host, int port, int timeout_ms) {
    // ...
}

The reason is that the default is applied by the caller's compiler. When main.cpp includes network.h and calls connect("example.com"), the compiler needs to see = 443 right there to rewrite the call. If the default lived only in network.cpp, other files would never see it, and connect("example.com") would fail to compile with "too few arguments".

That also explains a subtle maintenance fact: if you change a default value in a header, every file that calls the function must be recompiled, because the old value was baked into each call. The function's own .cpp file doesn't even change. Build systems handle this for you because they track header dependencies, but it matters for shared libraries: changing a default in a library header does not change behavior for programs compiled against the old header.

How default expressions are evaluated

A default doesn't have to be a literal. It can be any expression whose names are visible at the declaration, including a function call or a global variable. The expression is evaluated every time the default is used, at the moment of the call:

C++ Defaults are evaluated at each call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Some useful consequences:

  • A default like std::vector<int> v = {} creates a fresh empty vector for every call. C++ doesn't have the "shared mutable default" problem that Python's def f(items=[]) is famous for.
  • Default expressions can't use other parameters of the same function. void f(int a, int b = a); doesn't compile, because the order in which arguments are evaluated is unspecified.
  • Default expressions can't use local variables of the caller or of the function.

Keep defaults simple and obvious: constants, {}, or a named constexpr value such as default_timeout_ms. A default that calls a function with side effects (like make_id() above) surprises readers, because nothing at the call site shows that work is happening.

Default arguments and overloads

A default argument and an overload can express the same idea. These two designs are equivalent for callers:

C++
// One function with a default
void log(const std::string& message, int level = 1);

// Two overloads
void log(const std::string& message, int level);
void log(const std::string& message) { log(message, 1); }

Defaults are shorter. Overloads win when the "default" case needs different code, not just a different value, or when the default can't be written as an expression. You'll see overloading in detail in Function Overloading.

Don't mix both for the same arguments. If you declare log(const std::string&, int level = 1) and log(const std::string&), the call log("hi") matches both equally well, and the compiler reports an ambiguity:

TEXT
error: call of overloaded 'log(const char [3])' is ambiguous

Pitfalls with defaults

Boolean flags at the call site

A default bool parameter is tempting, but calls that do pass it become hard to read:

C++
save(document, true);   // true what? Overwrite? Compress? Ask first?

Prefer a scoped enum, which you'll meet in Enumerations. The call then explains itself:

C++ An enum instead of a bool flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Too many defaults

A function with five defaulted parameters forces callers to repeat four of them to change the fifth. When options pile up, group them in a struct with default member values. C++20 designated initializers then let callers name only what they change:

C++ An options struct with designated initializers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Designated initializers must follow the order the members are declared in (.port before .verbose), and any member you skip keeps its default. This gives you most of the readability of named arguments, using only standard C++. You'll learn more in Structs, Aggregates and Unions.

Defaults and virtual functions

One advanced trap is worth knowing now. Default arguments are chosen from the static type at the call site, while virtual functions are chosen from the dynamic type at run time. If a base class and a derived class give different defaults to an overridden function, calling through a base pointer runs the derived function with the base's default. The usual advice is: never give different defaults in overrides; better yet, don't put defaults on virtual functions at all. You'll see why in Virtual Functions and Polymorphism.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which declaration does NOT compile?

    Defaults must be trailing. Once a parameter has a default, every parameter to its right needs one too, and b has none.
  2. 2. Given void pad(std::string s, int width = 10, char fill = ' ');, how do you call it with fill set to '*' while keeping the default width?

    Arguments match parameters left to right and C++ has no named arguments, so to pass fill you must pass width as well.
  3. 3. You declare a function with a default in a header and define it in a .cpp file. Where should the default value appear?

    The caller's compiler inserts the default, so it must be visible in the declaration every caller includes. Repeating it on the definition is an error.
  4. 4. int counter = 0; int next() { return ++counter; } void show(int n = next()) { std::println("{}", n); } What do show(); show(); show(7); show(); print?

    The default expression runs at every call that uses it, and only then. show(7) doesn't call next(), so the values are 1, 2, 7, 3.

Summary

  • = value after a parameter in a declaration gives it a default; callers may then omit that argument.
  • Defaults must be trailing, and arguments match from the left, so you can't skip a parameter in the middle.
  • Give each default once, on the declaration. With headers, put defaults in the .h file, not the .cpp definition.
  • The compiler inserts defaults at each call site; changing a default requires recompiling the callers.
  • Default expressions are evaluated at every call that uses them and may not refer to other parameters.
  • Avoid ambiguous overload/default combinations, bool flags (use enum class), and long lists of defaults (use an options struct with designated initializers).

Next: Returning Values, where you'll return results efficiently, send back several values at once and say "maybe" with std::optional.