Why can't this be passed as the default parameter in a member function?

I tried to pass the current length value as a default parameter as an argument to a function. but the compiler shows an error that

"'this' cannot be used in this context"

Can anyone tell me what the mistake I made is.

class A { private: int length; public: A(); void display(int l=this->length) { cout<<"the length is "<<l<<endl; } }; int main() { A a; a.display(); return 0; } 
+4
source share
3 answers

Your member function:

 void display(int l=this->length) 

conceptually equivalent to this:

 void display(A * this, int l=this->length); //translated by the compiler 

which means that you use one parameter in the expression, which is the default argument for another parameter that is not allowed in C ++, because Β§8.3.6 / 9 (C ++ 03) says:

By default, arguments evaluate the time that the function calls. The order of evaluation of function arguments is undefined. Therefore, function parameters should not be used in the expression of default arguments , even if they are not evaluated.

Please note that C ++ does not allow this:

 int f(int a, int b = a); //illegal : Β§8.3.6/9 

The solution is to add one overload that does not accept any parameters:

 void display() { display(length); //call the other one! } 

If you do not want to add another function, select an impossible default value for the parameter. For example, since it describes a length that can never be negative, you can choose -1 as the default value, and you can implement your function as:

 void display(int l = -1) { if ( l <= -1 ) l = length; //use it as default value! //start using l } 
+12
source

Instead, you can overload and redirect data.

 class A { private: int length; public: A(); void display() { display(this->length); } void display(int l) { cout<<"the length is "<<l<<endl; } }; 
+3
source

There is no object at compile time, so it is not.

Why should you pass one of the properties of an object as the default value to a member function if that member function can access the property itself?

+1
source

All Articles