Learn C++
#include "functions/default_args.hpp"

Default Arguments in C++

//concept

Default arguments let callers omit trailing parameters: void greet(string name, string punct = "!") can be called with one or two arguments. They encode the common case once, keeping call sites short while preserving full control for the exceptions.

Defaults live in the declaration (usually the header), must trail all non-defaulted parameters, and are filled in at compile time at each call site. Combined with overloading they cover nearly all optional-parameter designs — though too many defaults on one function usually means it wants splitting or a config struct.

//how it works
1

Trailing defaults

void f(int a, int b = 5); allows f(1) and f(1, 2). Defaults must come last — no required parameter may follow a defaulted one.

2

Declared once, in the header

Put defaults on the declaration, not the definition — repeating them is an error, and callers only ever see the declaration.

3

Compile-time fill-in

The compiler inserts omitted arguments at each call, so defaults cost nothing at run time and work in constexpr contexts.

4

Defaults vs overloads

One function with defaults beats three near-identical overloads — until the behaviors genuinely diverge, when overloads win.

//example
#include <iostream>
#include <string>
 
void greet(const std::string& name, const std::string& punct = "!") {
std::cout << "Hi " << name << punct << std::endl;
}
 
int main() {
greet("Ada");
greet("Ada", "?");
return 0;
}
Output
Hi Ada!
Hi Ada?
1greet("Ada") omits punct, so the compiler supplies the default "!" — Hi Ada! prints.
2greet("Ada", "?") overrides the default explicitly, printing Hi Ada? instead.
3One definition served both call shapes with no duplicated logic.
//use cases
Logging and greeting helpers with a standard case plus rare overrides
Backward-compatible API growth: new behavior via a defaulted parameter
Config-ish functions (timeout = 30, retries = 3) with sane out-of-box values
Replacing clusters of trivial overloads with a single defaulted signature

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.