Default Arguments
Basic Syntax
#include <iostream>
using namespace std;
void greet(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!" << endl;
}
int main() {
greet("Alice"); // Output: Hello, Alice!
greet("Bob", "Good morning"); // Output: Good morning, Bob!
return 0;
}greet("Alice") is called with only one argument, the compiler fills in "Hello" for the missing greeting parameter automatically.Default Arguments Must Be Trailing
Once a parameter has a default value, every parameter after it must also have a default value. You cannot have a defaulted parameter followed by a non-defaulted one — the compiler needs to know, from left to right, exactly where the supplied arguments stop.
// OK: defaults are trailing (rightmost) void connect(string host, int port = 8080, bool useSSL = false); // ERROR: a non-default parameter cannot follow a default one // void connect(string host = "localhost", int port, bool useSSL);
Where to Put the Default: Declaration, Not Definition
// header.h
void greet(string name, string greeting = "Hello"); // default goes here
// source.cpp
#include "header.h"
void greet(string name, string greeting) { // no default here
cout << greeting << ", " << name << "!" << endl;
}Interaction with Function Overloading
Default arguments can create genuine ambiguity when combined with overloading: if a call could match more than one overload once defaults are taken into account, the compiler cannot decide which one you meant.
show(5) could match either overload once defaults are considered, and the compiler will reject it.void show(int a, int b = 10);
void show(int a);
int main() {
// show(5); // ERROR: ambiguous - matches show(int, int=10) and show(int)
show(5, 20); // fine - only show(int, int=10) can match
return 0;
}Key Points
A default argument supplies a fallback value used when the caller omits that parameter.
Parameters with defaults must be trailing - every parameter after the first default must also have one.
Put the default value in the declaration (header), not the definition, to avoid a redefinition error.
Default arguments combined with overloading can create ambiguous calls - design overload sets carefully.
Default arguments are resolved at compile time, based on the static number of arguments in the call.