I was trying to pass the current value of length as the default parameter as a function argument .
but compiler is showing error that
” ‘this’ may not be used in this context”
can any one tell me what is the mistake I have committed. ?
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;
}
Your member function:
is conceptually equivalent to this:
which means, you’re using one parameter in an expression which is the default argument for other parameter which is not allowed in C++, as §8.3.6/9 (C++03) says,
Note that C++ doesn’t allow this:
The solution is to add one overload which takes no parameter as:
If you don’t want to add one more function then choose an impossible default value for the parameter. For example, since it describes length which can never be negative, then you may choose
-1as the default value, and you may implement your function as: