Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of this sometimes necessary?

Tags:

c++

templates

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
like image 655
Ace7k3 Avatar asked Dec 19 '12 23:12

Ace7k3


1 Answers

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;
}
like image 176
Jesse Good Avatar answered Nov 17 '22 14:11

Jesse Good