Search code examples
c++c++11standardslanguage-designdefault-parameters

Why does C++ not allow a parameter to be a default argument?


void g(int n, decltype(n) = 0); // ok
void f(int n, int = n); // error : default argument references parameter 'n'

int main()
{
    f(1); // want it to be same as f(1, 1);
}

Why does C++ not allow a parameter to be a default argument?

What's the rationale?


Solution

  • One often-quoted potential rationale for that restriction is as follows: allowing parameters as default arguments would require imposing at least a partial ordering on parameter evaluation. Parameters that are used as default arguments in other parameters would have to be evaluated first.

    Meanwhile, C++ continues to stick to the original parameter evaluation approach: parameters are evaluated in unspecified order.

    The very same reasoning can be used to explain why one cannot refer to class members in default arguments of member functions: that would impose some ordering requirements on evaluation of hidden parameter this.