Restrictions on C++ Default Arguments

Of the operators, only the function call operator and the operator new can have default arguments when they are overloaded.

Arguments with default values must be the trailing arguments in the function declaration argument list. For example:

void f(int a, int b = 2, int c = 3);  // trailing defaults
void g(int a = 1, int b = 2, int c);  // error, leading defaults
void h(int a, int b = 3, int c);      // error, default in middle

Once a default argument has been given in a declaration or definition , you cannot redefine that argument, even to the same value. However, you can add default arguments not given in previous declarations. For example, the last declaration below attempts to redefine the default values for a and b:

void f(int a, int b, int c=1);     // valid
void f(int a, int b=1, int c);     // valid, add another default
void f(int a=1, int b, int c);     // valid, add another default
void f(int a=1, int b=1, int c=1); // error, redefined defaults

You can supply any default argument values in the function declaration or in the definition. All subsequent arguments must have default arguments supplied in this or a previous declaration of the function.

You cannot use local variables in default argument expressions. For example, the compiler generates errors for both function g() and function h() below:

void f(int a)
{
      int b=4;
      void g(int c=a); // Local variable "a" inaccessible
      void h(int d=b); // Local variable "b" inaccessible
}


new Operator
Default Arguments in C++ Functions
Evaluating C++ Default Arguments
Calling Functions and Passing Arguments