Please enable JavaScript to use CodeHS

Default Function Values in C++

By David Burnham

Introduction

One of the cool features of C++ is that it allows you to use default parameter values in your function. While this feature is not unique to C++, it is not seen in languages such as Java, and it is a nice feature to have.

A function default value is a value that can be used for a parameter if the calling statement does not pass an argument. If an argument is provided, the default value is ignored.

Basic Syntax

Function default values are assigned in the parameter list. After the parameter name, an assignment operator and value are used to denote a default value.

void funcName(type param = value) {
    // Code block
}
Plain text

Example:

// Function defintion
double pow(double base, int exp = 2){
    …
}

// Call using default values
cout << pow(3) << endl;

// Call overriding default value
cout << pow(2,4) << endl;
Plain text

In the example above, the first call only provides one parameter, which will be used as the base. Since the second parameter is not provided, the value of the exp parameter will be 2.

For the second call, a value is provided for the exp parameter, so the default value is ignored and exp will be equal to 4 for that call.

Take a look at this example in action.

Multiple Default Values

In C++, you can have multiple default values, for example:

void printTime(int hour = 12, int min = 00) {
    …
}
Plain text

There are a couple of things to keep in mind though. First, if you have a function that has multiple default values, the values are matched from left to right, so you can only leave off arguments to the right.

This means that in the example above, it is not possible to use a default value for hours without using the default value for minutes.

printTime(); // Uses default value for hours and minutes
printTime(11); // Uses 11 for hours and default value for minutes
printTime(11, 15); // Uses 11 for hours and 15 for minutes
Plain text

Second, regardless of how many default values you use, the default values need to be your last parameters.

Valid: Default value is after non-default value

void printTime(int hour, int min = 00) {
    …
}
Plain text

Invalid: Default value is before non-default value

void printTime(int hour = 12, int min) {
    …
}
Plain text

Take a look at this example in action.

Your Turn

You have been put in charge of creating an app that enters orders for a fast-food restaurant. Fort his exercise write a function called printMeal that will print an order out. The meal should take a main item (required) and a size (optional). The default size should be medium, but you should be able to override this with either a small, larger, or none. The app should then take this input and output the order. For example:

printMeal("Cheeseburger", "large"); should print Cheeseburger with large fries and large drink.

printMeal("Cheeseburger", "no"); should print Cheeseburger with no fries and no drink.