Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 824
xmllmx Avatar asked Oct 26 '25 08:10

xmllmx


1 Answers

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.

like image 88
AnT Avatar answered Oct 28 '25 23:10

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!