just stumbled upon something i can’t explain. The following code doesn’t 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 i change _attr = 3; to this->attr = 3; there seems to be no problem.
Why is that? Are there any cases you must to use this?
I used g++ test.cpp -Wall -pedantic to compile and i get the following error
test.cpp: in member function 'void super<b>::foo()':
test.cpp:11:3: error: '_attr' was not declared in this scope
Why is that? Are there any cases you must to use this?Yes, there are some cases where you need to use
this. In your example, when the compiler sees_attr, it tries to look for_attrinside the class and cannot find it. By addingthis->you delay lookup until instantiation time which allows the compiler to find it inside ofsub.Another very common reason to use this is to resolve ambiguity problems: