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.
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.
Example:
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.
In C++, you can have multiple default values, for example:
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.
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
Invalid: Default value is before non-default value
Take a look at this example in action.
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
.