Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this can not be passed as default parameter in member function?

Tags:

c++

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;

}
like image 692
Abhishek Gupta Avatar asked Jun 23 '12 05:06

Abhishek Gupta


2 Answers

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 
}
like image 75
Nawaz Avatar answered Sep 20 '22 07:09

Nawaz


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;
    }
};
like image 25
Michael Anderson Avatar answered Sep 21 '22 07:09

Michael Anderson