Default Arguments in C++



Default Arguments

Default arguments in C++ are the values that are assigned to function parameters during function declaration. These default values are automatically assigned when the caller does not provide any arguments for those parameters while calling the function. If a value is provided by the caller during a function call, it will override the default value.

Syntax

return_type function_name(param1 = v1, param2 = v2, ...);

Here

  • return_type defines the type of returned value e.g., int, float, void.
  • function_name is the name of the function defined by the user
  • param1, and param2 are the names of function parameter.
  • v1, and v2 are default values assigned to those parameters.

Rules for Default Arguments

Here are the key rules to follow when defining default arguments in C++ to ensure that your code is both efficient and error-free.

1. Default Arguments must be specified in Function Declaration, not Definition.

The first rule says that default arguments must be specified in the function declaration (prototype), not in the function definition (implementation).
In case the default argument is specified in the definition, or if in both the declaration and definition, then it will throw a compilation error.

Example

// Function Declaration with default arguments
void greet(string name = "TutorialsPoint");

// Function Definition without default arguments (Correct)
void greet(string name) {
    cout << message << ", " << name << "!" << endl;
}

2. Default Arguments must be assigned from Right to Left

When assigning the values for default arguments, it must start from the rightmost parameters to the leftmost ones, where the user can't skip providing parameters in the middle.

Example

// Valid
void funcA(int x, string y = "TutorialsPoint");

// Valid
void funcB(int x = 2006, string y = "TutorialsPoint" );

// Invalid, because default arguments must be assigned from right to left
void funcC(int x = 2006, int y);

3. Default Arguments cannot be Changed or Modified

Once specified default argument in the function declaration, then further it can't be changed or modified in any other declaration or definition. Else it will throw an error.

Example

void func(int x = 10);  // First Declaration
void func(int x = 20);  // Second Declaration, causes error

4. Ambiguity with Function Overloading

Calling the default arguments from overloaded functions can cause ambiguity, making it difficult for the compiler to decide which version of the function to call if the arguments provided are not unique. So for this ensure that functions with default arguments do not conflict with each other in overloads.

Example

void get(string name = "TutorialsPoint");   // function 1
void get(string name = "TutorialsPoint", int num = 2016);  // function 2

get();  // Which function should the compiler choose?

Example of Default Arguments

Here is a basic simple example showcasing Default arguments in C++.

#include <iostream>
using namespace std;

int main() {
    double price, discount = 12.0;  // Default discount

    cout << "Enter the price of the item: ";
    cin >> price;

    double total = price - (price * discount / 100);
    cout << "The total price after a " << discount << "% discount is: " << total << endl;

    return 0;
}

When the above code is compiled and executed, it produces the following result −

Enter the price of the item: 120
The total price after a 12% discount is: 105.6

Default Argument as an Expression

When defining a function, the user can specify the default values for parameters, where these default values can be a constant value or an expression (involving variables, constants, or function calls), which is evaluated when the function is called.

Example

Here is the following example for the default function argument.

#include <iostream>
using namespace std;

double total_price(double price, double discount = 12.0) {
    return price - (price * discount / 100);
}

int main() {
    double price;

    cout << "Enter the price of the item: ";
    cin >> price;

    // Calculate the total price with a 12% discount by default
    double total = total_price(price);

    cout << "The total price after a 12% discount is: " << total << endl;

    return 0;
}

When the above code is compiled and executed, it produces the following result −

Enter the price of the item: 120
The total price after a 12% discount is: 105.6

Default Argument as a Function Call

Calling a function to determine the default value is known as default argument as a Function Call. This calculates the default value dynamically based on the function's logic or other parameters.

#include <iostream>
#include <cmath>  // for value of 
using namespace std;

double getDefaultWidth() {
    return 5.0;
}
double getDefaultRadius() {
    return 3.0; 
}

double cuboid_vol(double l, double h, double w = getDefaultWidth()) {
    return l * w * h;
}
double cylinder_vol(double h, double r = getDefaultRadius()) {
    return M_PI * r * r * h;  
}

int main() {
    double length = 10.0; 
    double height = 7.0; 

    // Volume of Cuboid with default width
    cout << "Cuboid volume : " << cuboid_vol(length, height) << " cubic units" << endl;

    // Volume of a cuboid with a custom width
    cout << "Cuboid volume (custom width): " << cuboid_vol(length, height, 4.0) << " cubic units" << endl;

    // Volume of cylinder with default radius
    cout << "Cylinder volume (default radius): " << cylinder_vol(height) << " cubic units" << endl;

    // Volume of a cylinder with a custom radius
    cout << "Cylinder volume (custom radius): " << cylinder_vol(height, 6.0) << " cubic units" << endl;

    return 0;
}

When the above code is compiled and executed, it produces the following result −

Cuboid volume : 350 cubic units
Cuboid volume (custom width): 280 cubic units
Cylinder volume (default radius): 197.92 cubic units
Cylinder volume (custom radius): 791.681 cubic units

Advantages of Default Arguments

  1. It simplifies the function calls by reducing the number of overloads, where users don't need to create multiple overloaded functions when one function can handle different cases by using default values for parameters.
  2. Default arguments help avoid code duplication and reduce redundancy.
  3. It improves code readability and increases flexibility, which makes further easier to modify in the future.
Advertisements