Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default arguments have to be bound at compiled time - why? [closed]

Why was C++ designed like this?...

(This question is different, but intimately related to

Not possible: this pointer as a default argument. Why? )

like image 776
alexandreC Avatar asked Dec 20 '22 14:12

alexandreC


1 Answers

Actually, that's not completely accurate. The restrictions are:

8.3.6 Default arguments [dcl.fct.default]

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.

like image 172
Luchian Grigore Avatar answered Dec 23 '22 04:12

Luchian Grigore