Default Parameters
Lesson outline
In-Depth Rules
Default parameters must be specified from right to left in the parameter list. Once a parameter is given a default value, all parameters to its right must also have defaults.
Provide a parameter's default at most once in a given scope - usually in a header declaration. Do not repeat the same default in both a declaration and a definition.
Default arguments are looked up and bound at the call site. The default must therefore be visible to the caller. If you change a default in a header, callers must be recompiled to pick it up.
Advanced Usage
A default argument can be almost any expression that is valid at the call site, including function calls. It does NOT have to be a compile-time constant. The expression is evaluated each time the call uses the default.
Later parameters' defaults can refer to earlier parameters in the same parameter list, but not vice versa.
Templated Defaults
Templates can also provide defaults - for template parameters and for function parameters inside templates - reducing verbosity for common cases.
Design Considerations
Default parameters can improve convenience but may also reduce clarity. Consider:
- Using overloads when different parameter combinations change behavior significantly.
- Documenting defaults clearly where the function is declared (headers).
- Avoiding defaults with surprising side effects (e.g., calling a function with observable state changes).
- Being careful when mixing overloads and defaults—certain combinations can create ambiguous calls.