Why was C++ designed like this?...
(This question is different, but intimately related to
Not possible: this pointer as a default argument. Why? )
Actually, that's not completely accurate. The restrictions are:
7) Local variables shall not be used in a default argument. [ Example:
void f() {
int i;
extern void g(int x = i); //error
// ...
}
—end example ]
8) The keyword
this
shall not be used in a default argument of a member function. [ Example:
class A {
void f(A* p = this) { } // error
};
So, this
and local variables can't be used as defaults.
For example, the following is valid:
int a = 1;
int f(int);
int g(int x = f(a)); // default argument: f(::a)
void h() {
a = 2;
{
int a = 3;
g(); // g(f(::a))
}
}
g
will be called with the value f(2)
, which isn't a compile-time constant. This is an example straight from the standard.
The reasons it's like this is the usual: there either wasn't a proposal for it, or it was rejected, deemed not necessary or too difficult to implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With