Search code examples
c++thisdefault-argumentsthis-pointer

I am unable to use a class variable as a default argument for the same class's function


I am well aware that line 7 is invalid . but I want to use the class variables as default argument to method(apple) .

class trial{

public:

int i=10 ;

    void apple(int i=this.i){
       cout<<i<<endl;
    }

    void display(){
         cout<<i<<endl;
    }
};

Solution

  • Replace

    void apple(int i=this.i){
         cout<<i<<endl;
    }
    

    … with

    void apple(int i){
         cout<<i<<endl;
    }
    
    void apple(){
         apple(i);
    }
    

    You can't access member variables in the formal argument list of a function.