Default arguments in C++ allow developers to specify default values for function parameters. This feature enhances code flexibility and readability by enabling function calls with fewer arguments.
Default arguments are predefined values assigned to function parameters. When a function is called without providing all arguments, these default values are used. This mechanism simplifies function calls and reduces code duplication.
To define a default argument, assign a value to the parameter in the function declaration:
return_type function_name(type1 param1, type2 param2 = default_value);
Here's a practical example:
void greet(std::string name = "Guest") {
std::cout << "Hello, " << name << "!" << std::endl;
}
int main() {
greet(); // Outputs: Hello, Guest!
greet("Alice"); // Outputs: Hello, Alice!
return 0;
}
Functions can have multiple default arguments. This feature is particularly useful for functions with numerous parameters where some have common default values.
int calculate(int a, int b = 1, int c = 0) {
return a * b + c;
}
int main() {
std::cout << calculate(5); // Outputs: 5
std::cout << calculate(5, 2); // Outputs: 10
std::cout << calculate(5, 2, 3); // Outputs: 13
return 0;
}
Default arguments in C++ offer a powerful way to create more flexible and maintainable code. By understanding their syntax and best practices, developers can write cleaner, more efficient functions. As you continue to explore C++ features, consider how default arguments can be integrated with other concepts like Function Overloading and Templates to create robust and adaptable code.