1

what is the difference between this:

int MyClass::getId() {
    return this->id;
}

and this:

int MyClass::getId() {
    return id;
}

in C++?

Accumulator
  • 873
  • 1
  • 13
  • 34
  • Quite a few existing posts on this. http://stackoverflow.com/questions/6779645/use-of-this-keyword-in-c – davepmiller Jul 12 '15 at 22:34
  • i didnt know what to put in the search and the automatic title search nor google didn't give any good results – Accumulator Jul 12 '15 at 22:35
  • There *is* a difference, but it only arises in convoluted cases of template sorcery under specific conditions, so you'll probably never encounter it. – Quentin Jul 12 '15 at 22:38
  • If you have no shadowed variables then there is no difference. If you have shadowed variables then you have much bigger issues in your code base anyway. Turn on your compiler warnings to make sure you have no shadowed variables. – Martin York Jul 13 '15 at 02:08

3 Answers3

2

The first example limits the scope where the name "id" is looked up to members of class MyClass.

the second example does not.

This makes a difference if e.g. MyClass has no member "id", or if the current method has a local variable or parameter with the same name.

Ludwig Schulze
  • 2,155
  • 1
  • 17
  • 36
1

It depends on the context. Examples:

template <typename> struct X { int a; };

int b;

template <typename T> struct Foo : X<T> {
    int f() {
        return this->a;    // OK
        // return a;       // Error
    }

    int g() {
        // return this->b; // Error
        return b;          // OK
    }
};
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

Assuming your class has a member variable named id, there is no difference. Even if you have a global id variable, the member variable always takes precedence.

Your next question is: So why does exist the this keyword?

There are some situations you absolutely need it.

One example is you want a function returning a pointer/reference(*) to the object itself:

return *this;    //reference
return this;     //pointer

Other is you want to pass it as an argument to a function

some_function(*this);    //reference(&) or value, depends on some_function signature
some_function(this);     //pointer

It can also be used in this->id, just for legibility, just for the next person reading the code immediately know id is a constituent of the class instead of a global, having no functional advantage.

If you use a debugger, the this may be also an inspectable variable by it.

sergiol
  • 4,122
  • 4
  • 47
  • 81