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 _attr
inside the class and cannot find it. By adding this->
you delay lookup until instantiation time which allows the compiler to find it inside of sub
.
Another very common reason to use this is to resolve ambiguity problems:
void foo (int i)
{
this->i = i;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With