C++ default arguments
Created By: chatGPT
Default arguments in C++ allow a function to be called with fewer arguments than declared. When a parameter has a default value, you can skip it in the function call, and the default value will be used instead. This feature helps to reduce code complexity and make function calls easier. Default arguments are specified in the function declaration and not in the function definition. Here’s a brief example to illustrate how this works:
cpp
#include <iostream>
// Function declaration with default arguments
void display(int x, int y = 10) {
std::cout << "Value of x: " << x << " and y: " << y << std::endl;
}
int main() {
display(5); // Calls display with x = 5, y uses default value 10
display(5, 15); // Calls display with x = 5, y = 15
return 0;
}
In the example above, the function display has two parameters. The second parameter, y, has a default value of 10. When display(5) is called, it will use the default value for y, while in the second call, display(5, 15), both arguments are provided. It’s important to note that default arguments must appear from right to left, meaning once a parameter is assigned a default value, all subsequent parameters must also have default values.
cpp
// Incorrect example - will cause a compilation error
void incorrectFunc(int x, int y = 10, int z);
// This declaration is invalid because the parameter z has no default value
You can also use default arguments with function overloading. As long as the overloaded functions have different signatures, you can define default arguments in each function. Here's an example showcasing this capability:
When using default arguments, be cautious of the scope and ensure you provide defaults for the appropriate functions. Also, remember that default arguments must be defined in the function declaration, not in the definition. This principle helps maintain clarity and intent in code while leveraging the flexibility of default values.cpp
#include <iostream>
void display(int x, int y = 10) {
std::cout << "Display with two parameters: " << x << " and " << y << std::endl;
}
void display(double x, double y = 7.5) {
std::cout << "Display with double parameters: " << x << " and " << y << std::endl;
}
int main() {
display(5); // Calls the first display
display(5, 15); // Calls the first display with both parameters
display(3.5); // Calls the second display
return 0;
}