We define functions that take defaults arguments. Compiler handles default arguments during the call time.

For example,

int add(int a, int b = 2)
{
    return a + b;
}
 
add(1);

When compiler encounters add(1), compiler rewrites it as add(1, 2).

A function can have multiple defaults arguments.

Rules for Default Arguments

There are following rules that have to be kept in mind:

  1. Default arguments are always come after non-default arguments.
void print(int a = 1, int b); // wrong
void print(int a, int b = 1); // correct
  1. There should not be a non-default argument in between defaults arguments.
  2. Default arguments should be declared once in a same transaction unit. This means that default arguments should either be declared in forward declaration or in definition. For example,
// wrong
void print(int value, char delimiter = '\n');
 
void print(int value, char delimiter = '\n') // compilation error
{
    std::cout << value << delimiter;
}
 
// corrected
void print(int value, char delimiter = '\n');
 
void print(int value, char delimiter)
{
    std::cout << value << delimiter;
}

Also, default arguments must be declared in a translation unit before the usage. For example,

void print(int value, char delimiter)
{
    std::cout << value << delimiter;
}
int main(int argc, char const *argv[])
{
    print(1);
    return 0;
}
 
void print(int value, char delimiter = '\n');

When compiled, compiler will cry as print requires two arguments. Compiler does not know about default argument until it reaches the declaration in the bottom.

Thumb Rule

If the function has forward declaration and it is stored in header file, always put default arguments declaration there.

References

  1. https://www.learncpp.com/cpp-tutorial/default-arguments/