struct X
{
X():mem(42){}
void f(int param = mem) //ERROR
{
//do something
}
private:
int mem;
};
Can anyone give me just one reason as to why this is illegal in C++?! That is to say, I know that it is an error, I know what the error means, I just can’t understand why would this be illegal!
Your code (simplified):
You want to use a non-static member data as default value for a parameter of a member function. The first question which comes to mind is this : which specific instance of the class the default value
membelongs to?Your answer might be
100asf()is invoked on the objectx1which hasmem = 100. If so, then it requires the implementation to implementf()as:which in turn requires the first argument to be initialized first before initialization of other argument. But the C++ standard doesn’t specify any initialization order of the function arguments. Hence that isn’t allowed. Its for the same reason that C++ Standard doesn’t allow even this:
In fact, §8.3.6/9 explicitly says,
And rest of the section is an interesting read.
An interesting topic related to “default” arguments (not related to this topic though):