Default Arguments in C++
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.
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.
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.
Compile-time fill-in
The compiler inserts omitted arguments at each call, so defaults cost nothing at run time and work in constexpr contexts.
Defaults vs overloads
One function with defaults beats three near-identical overloads — until the behaviors genuinely diverge, when overloads win.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.