prelic prelic - 21 days ago 5
C++ Question

When is 'this' required?

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.

Answer

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.