Topic 32 of 83
Default Arguments
Overview
Default arguments allow you to omit certain arguments when calling a function, falling back to a predefined default value.
Syntax
cpp
// Default arguments must be at the END of the parameter list
void createProfile(string name, int age = 18, string country = "Unknown") {
// ...
}
int main() {
createProfile("Alice"); // age=18, country="Unknown"
createProfile("Bob", 25); // country="Unknown"
}Common Pitfalls
- Putting default arguments on the left side of the parameter list (e.g., `void func(int x = 5, int y)` is illegal).
Interview Tips
- Rule: If a parameter has a default argument, all subsequent parameters to its right MUST also have default arguments.
- If a function is declared in a header file, place the default arguments in the declaration (prototype), not the definition.
Real-World Example
A flexible logging system.
example
cpp
#include <iostream>
using namespace std;
void log(string message, string level = "INFO") {
cout << "[" << level << "] " << message << endl;
}
int main() {
log("System booted"); // Uses "INFO"
log("Database failed", "ERROR"); // Overrides default
return 0;
}