this in constructor | error

Hi all,
I have this code:
1
2
3
4
5
6
7
8
class Numbers {
    private:
        int a;
        int b;
        
    public:
        Numbers( int a, int b ) : this->a( a ), this->b( b ) {}        
};

It gives an error on line 7: exspected identifier before "this". What is wrong?
If I remove the "this->" parts, it works fine.
Last edited on
You shall use either qualified (for hidden base classes) or unqualified identifiers. this is not allowed. However you can use it inside the initialization expression. Here are examples of correct usage

1
2
3
4
5
6
7
8
 class Numbers {
    private:
        int a;
        int b;
        
    public:
        Numbers( int a, int b ) : a( a ), b( b ) {}        
};


a and b before expresions enclosed in parentheses are class members. a and b inside the parentheses are parameters.
1
2
3
4
5
6
7
8
 class Numbers {
    private:
        int a;
        int b;
        
    public:
        Numbers( int a, int b ) : a( a ), b( this->a + b ) {}        
};


Again a and b before expressions enclosed in parentheses are class members. Inside the second expression member this-a is added with parameter b.
Last edited on
Topic archived. No new replies allowed.