Skip to main content

Write a cpp program which explains the concept of default arguments.

In C++, default arguments are values that are automatically assigned to function parameters if the caller does not provide a corresponding argument when calling the function. Default arguments can be used to specify a standard or fallback value for a function parameter, which allows the caller to omit that argument if they want to use the default value.

#include <iostream>
using namespace std;

// default arguments
int person(int age = 0, string fname = "No First Name", string lname = "No Last Name")
{
cout << "Age: " << age << endl;
cout << "First Name: " << fname << endl;
cout << "Last Name: " << lname
<< endl
<< endl;
return 0;
}

void main()
{
// Call the function with only the first argument
person();

// Call the function with the first and second arguments
person(25, "Jane");

// Call the function with all three arguments
person(25, "Jane", "Doe");

return 0;
}

Output:

Age: 0
First Name: No First Name
Last Name: No Last Name

Age: 25
First Name: Jane
Last Name: No Last Name

Age: 25
First Name: Jane
Last Name: Doe

Explanation

In the above program, the function person() has three parameters, age, fname, and lname. The first two parameters have default arguments, which means that if the caller does not provide a value for these parameters, the default values will be used instead.

The first call to person() does not provide any arguments, so the default values are used for the first two parameters. The third parameter, lname, does not have a default argument, so the caller must provide a value for it.

The second call to person() provides a value for the first parameter, but not for the second parameter. The default value is used for the second parameter.

The third call to person() provides values for all three parameters, so the default values are not used.