Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the "this" pointer inside a class

Tags:

c++

pointers

this

the question is simple... is there any difference in using this->yourvariable or yourvariable directly for some reason?

I am not finding any problem with that, but I am using this-> a lot and would like to know if there is any difference before going further.

I saw a comment on a post here and I don't remember which thread, but the person said something about using the keyword "this".

Personally, I find it nice to use than the variable directly. It makes the code more easier and pretty.

Joe

like image 409
Jonathan Avatar asked Oct 22 '09 21:10

Jonathan


2 Answers

In most cases there is no difference. But there are situations where it makes a difference:

class foo
{
    int i;
    void bar() {
        int i = 3;
        i; // refers to local i
        this->i; // refers to the member i
    }
};

Also, with templates you may need to qualify a member with this-> so that name lookup is delayed:

template<typename T>
struct A
{
    int i;
    T* p;
};

template<typename T>
struct B : A<T>
{
    void foo() {
        int k = this->i; // here this-> is required
    }
};

A compiler that properly does the "two phase lookup" will complain in case you remove "this->" that it doesn't know what i is supposed to be. "this->" tells it that it's a member from a base class. Since the base class depends on a template parameter, lookup is delayed until the class template is instantiated.

like image 78
sellibitze Avatar answered Oct 13 '22 07:10

sellibitze


No, there is no real difference, it is simply a scope qualifier. However, suppose a method

void SetFoo( Foo foo )
{
    this->foo = foo;
}

where this->foo is a private member. Here it allows you to take a parameter with the same name as a class/instance variable.

like image 28
Ed S. Avatar answered Oct 13 '22 06:10

Ed S.