Is using this sometimes necessary?

just stumbled upon something that I can’t explain. The following code does not compile

template<int a> class sub{ protected: int _attr; }; template<int b> class super : public sub<b>{ public: void foo(){ _attr = 3; } }; int main(){ super<4> obj; obj.foo(); } 

whereas when changing _attr = 3; before this->attr = 3; the problem does not arise.

Why? Are there any cases where you should use this?

I used g++ test.cpp -Wall -pedantic to compile and I got the following error:

 test.cpp: in member function 'void super<b>::foo()': test.cpp:11:3: error: '_attr' was not declared in this scope 
+6
source share
1 answer

Why is that? Are there any cases you must to use this?

Yes, there are times when you need to use this . In your example, when the compiler sees _attr , it tries to look for _attr inside the class and cannot find it. By adding this-> , you drag out the search until you instantiate it, which allows the compiler to find it inside sub .

Another common reason to use this problem is to solve uncertainty problems:

 void foo (int i) { this->i = i; } 
+7
source

All Articles