Is the this
pointer ever required? I guess you'd need it if you were functionally passing around the instance of the class pointed to by this
. But in terms of setting/retrieving/calling/whatever members, is this
always optional?
I've tagged this C++ because that's the language I'm specifically wondering about, but if someone can confirm that the construct is the same for Java and other OO languages that use a this
pointer, it'd be appreciated.
There's three cases I can think of:
When you simply want to pass a pointer to the current class:
class B;
struct A {
B* parent_;
A(B* parent) : parent_(parent) {}
};
struct B {
A* a;
B() : a(new A(this)) {}
};
In a constructor or member function, where a member is shadowed by an argument:
struct A {
int a;
void set_a(int a) { this->a = a; }
};
Here, the member variable "a" is shadowed by the argument "a", so this->
is used to access the member instead of the argument.
(example above edited to be a function rather than constructor, since you wouldn't normally assign this way in a constructor)
When accessing a public/protected member variable or function in a base class of a template class
template <class T>
struct A {
int a;
};
template <class T>
struct B : public A<T> {
int f() { return this->a; }
}
here, a
alone would not be a dependent name, so the compiler would expect to find a declaration of it in B
or a base of B
that does not depend on T
. Adding this->
makes the lookup dependent on the type of this
, and since this
is a dependent type, the lookup of a
is deferred until f()
is instantiated.
One could write return A::a
instead of return this->a
, but in the presence of multiple bases, whether direct or indirect, using this->
is more flexible. This alternative syntax is also limited to member variables and non-virtual functions - if it is used with a virtual function, it the function will be called directly instead of doing virtual function call.
You need it when you have a local variable that has the exact same name as the member variable. In this case, the local variable is said to shadow the member variable. To get to the member variable in this situation, you must use this
.
Some people consider it good practice to explicitly mention that the variable you are modifying is a member variable by using this
all the time, but this is not always the case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With