tags:

views:

428

answers:

4

Hi,

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

+10  A: 

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.

Ed Swangren
A: 

This was kind of asked and answered about C# here and I think that the answer (at least mine) is the same. It is preference.

Brian ONeil
A: 

I find that using this makes my code more readable, but there's no reason that you have to. If you look at the assembler code your compiler generates, it should be functionally (and usually literally) identical.

Basically, when the function is called, it is passed a hidden argument this which is then used to figure out which variables are where. If you use the variables directly, without a this->, you're not doing anything except making use of some syntactic sugar.

pavpanchekha
+12  A: 

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.

sellibitze
+1 for signalling the template issue. gcc usually says something along the line of '<variable> does not depend on a template parameter so a definition must be available'.
Matthieu M.