Default parameters

Table of Contents

1. Default parameters

When declaring a function, you can also set default parameters. These are the default values assigned to the parameters if the user doesn't pass anything in. The default parameters are only specified in a function declaration - NOT the definition!

In this example, it could be a function that displays ingredients for a recipe, and by default the batch is set to 1.0 (one batch).

void OutputIngredients( float eggs, float sugar, float flour, float batch = 1.0 );

The function could be called without passing in a batch:

cout << "Ingredients:" << endl;
OutputIngredients( 1, 2.0, 3.5 );

Or they could pass a batch amount explicitly:

cout << "Ingredients:" << endl;
OutputIngredients( 1, 2.0, 3.5, 0.5 );  // half batch

You can have multiple default parameters specified in your function declaration - but all variables with default values must go after any variables without default values.


Example usage - Logger

In the Overloaded Functions part we showed having a Logger class with multiple constructors. With this particular example, it would actually be better to use a default parameter instead of overloading!

Here's an example using the default paramter:

Logger.h

class Logger
{
  public:
  Logger( std::string filename = "log.txt"  );
  ~Logger();                      // destructor
  // ... etc ...

  private:
  ofstream m_outfile;
  // ... etc ...
};

Logger.cpp

Logger::Logger( std::string filename /*="log.txt"*/ )
{
  m_outfile.open( filename );
}

Loger::~Logger()
{
  m_outfile.close();
}

Elseware in the program, the Logger will be created, and that log file will be opened automatically. We can specify a file or not, and both will use the same constructor:

Logger logger();
Logger logger( "log-sept-28.txt" );

1.1. Additional notes


Author: Rachel Wil Sha Singh

Created: 2023-09-28 Thu 15:34

Validate