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:
void display(int l=this->length)
is conceptually equivalent to this:
void display(A * this, int l=this->length); //translated by the compiler
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,
Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated.
Note that C++ doesn't allow this:
int f(int a, int b = a); //illegal : §8.3.6/9
The solution is to add one overload which takes no parameter as:
void display()
{
display(length); //call the other one!
}
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 -1
as the default value, and you may implement your function as:
void display(int l = -1)
{
if ( l <= -1 )
l = length; //use it as default value!
//start using l
}
You could user overloading and forwarding instead.
class A
{
private:
int length;
public:
A();
void display()
{
display(this->length);
}
void display(int l)
{
cout<<"the length is "<<l<<endl;
}
};
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