TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  PCA#007Checked automatically with code checker

Synopsis:Use overloaded functions instead of default arguments
Language:C++
Severity Level:9
Category:Parts of C++ to Avoid


Description:

Define a set of overloaded functions instead of using default arguments.

The mechanism is more powerful than default arguments:

  • Default arguments can only be specified for the last arguments.
  • An overloading function can provide a default value for any argument by delegation. The value of the missing argument can be determined using more elaborate computations than is possible with default arguments (see example below).
  • Overloaded functions eliminate the problem of whether the default value should be specified in the function's declaration or definition: [INT#028].

example:

Instead of writing a function with a default argument:

void  // declaration; definition omitted
PrintName(
  std::string name,
  bool uppercase = false);

define a set of overloaded functions:

inline void  // definitions; declarations omitted
PrintName(
  std::string name)
{
  bool uppercase = is_local(name);  // determine value missing arg
  PrintName(name, uppercase);       // delegate to two arg version
}

void
PrintName(
  std::string name,
  bool uppercase)
{
  // actual implementation to print the name with specified case
}

Exception:

Because it is not possible to delegate a constructor's implementation to another constructor, it can be useful to supply default arguments with constructors.