C++ Default Parameters

When defining a function in C++, you have the option to provide default values for some or all of the parameters. This means that if a caller of the function does not provide a value for a particular parameter, the default value will be used instead. Here's how you can define and use default parameters in C++:

Step 1: Declare the function

You start by declaring the function in your class or code file, just like any other function. The declaration includes the function name, return type, and the parameter list. However, in this case, you will also include the default values for the parameters you want to have defaults for.

Step 2: Define the function

After declaring the function, you need to define it. The definition includes the actual implementation of the function. Here, you will specify the default values for the parameters just like you did in the declaration.

Step 3: Call the function

When you call the function, you have the option to provide arguments for the parameters. If you do not provide an argument for a parameter that has a default value, the default value will be used.

That's it! By providing default values for parameters, you allow callers of the function to omit those parameters if they are not needed, simplifying the function call and making the code more readable.

Here is an example to illustrate the usage of default parameters in C++:

#include <iostream>

// Step 1: Declare the function with default parameters
void greet(std::string name = "World", int times = 1);

int main() {
    // Step 3: Call the function without providing arguments
    greet();  // Output: Hello, World!

    // Step 3: Call the function with arguments
    greet("Alice", 3);  // Output: Hello, Alice! (3 times)

    return 0;
}

// Step 2: Define the function with default parameter values
void greet(std::string name, int times) {
    for (int i = 0; i < times; i++) {
        std::cout << "Hello, " << name << "!" << std::endl;
    }
}

In this example, the greet function has two parameters: name and times. Both parameters have default values specified in the function declaration. When the function is called without providing any arguments, the default values "World" and 1 are used for name and times respectively. When the function is called with arguments, the provided values are used instead.

I hope this explanation helps! Let me know if you have any further questions.