简体   繁体   中英

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

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;
    }
};

At compile time, there is no object, so there is no this.

Why would you pass in one of your object's properties as a default value into a member function if that member function can access the property itself?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM