prelic prelic - 2 months ago 10
C++ Question

When is 'this' required?

Is the

pointer ever required? I guess you'd need it if you were functionally passing around the instance of the class pointed to by
. But in terms of setting/retrieving/calling/whatever members, is
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
pointer, it'd be appreciated.


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.