Unit 13: Default parameters

  1. Default parameters
  2. Overloading functions vs. default parameters
  3. Default parameter rules

  4. Example code and additional resources

This week's stuff:

Default parameters

Default parameters let us define a "default value" for one or more parameters of a function, which are specified in the function's declaration.

The function with default parameters will contain the maximum amount of parameters. When the function is called, any data not passed in as an argument will receive the default value instead.

// ONE FUNCTION USING DEFAULT PARAMETERS:
void Setup( string log_file = "log.txt", bool is_debug = false );

This is different from function overloading, since we won't have different versions of functions with increasing amount of parameters.

// OVERLOADED FUNCTIONS:
void Setup( string log_file );
void Setup( string log_file, bool is_debug );

Overloading functions vs. default parameters

  • Overloading functions and using default parameters are two strategies we can use to reduce duplicate code in our programs.
  • Using function overloading is best when you have different types of information that could go into a function.
  • Default parameters are best when the set of information is the same, but some information may be missing.


Better use of default parameters - the parameters are the same, but may need default values.

// ONE FUNCTION USING DEFAULT PARAMETERS:
void Setup( string log_file = "log.txt", bool is_debug = false );

Better use of function overloading - the data is different for each function.

void Draw( Rectangle rect );
void Draw( Circle circle );

Default parameter rules

When declaring a function with default parameters, we specify the default values in the declaration only:

// DECLARATION
void Setup( string log_file = "log.txt", bool is_debug = false );

The definition won't have the value specified, but it is common to write the default value out in a comment:

// DEFINITION
void Setup( string log_file /*= "log.txt"*/, bool is_debug /*= false*/ )
{
	this->my_ifstream.open( log_file );
	this->debug = is_debug;
}
  • Not every parameter has to have a default value, you could have some parameters that are always required.
  • If you specify a default parameter, each parameter after it must also have a default.

Example code and additional resources

Spring 2024 lecture:

  • WORK IN PROGRESS