what is the difference between this:
int MyClass::getId() {
return this->id;
}
and this:
int MyClass::getId() {
return id;
}
in C++?
what is the difference between this:
int MyClass::getId() {
return this->id;
}
and this:
int MyClass::getId() {
return id;
}
in C++?
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.
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
}
};
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.