I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
public Light(Vector v)
{
this.dir = new Vector(v);
}
Elsewhere
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use
this
to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what
base<T>
could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent callf
that seems just natural to the programmer is a symbol that the compiler must find as a member ofderived
or in enclosing namespaces --which does not happen in the example-- and it will complain.The solution is turning the non-dependent name
f
into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f
--adding thebase<T>
makes the symbol dependent onT
and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a
this->
before the symbol. As the template class you are implementing does depend on an argument (it inherits frombase<T>
)this->
is argument dependent, and we get the same result:this->f
is checked in the second round, after template parameter substitution.I only use it when absolutely necessary, ie, when another variable is shadowing another. Such as here:
Or as Ryan Fox points out, when you need to pass this as a parameter. (Local variables have precedence over member variables)
I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.
I tend to underscore fields with _ so don't really ever need to use this. Also R# tends to refactor them away anyway...
I use it only when required, except for symmetric operations which due to single argument polymorphism have to be put into methods of one side:
[C++]
this is used in the assignment operator where most of the time you have to check and prevent strange (unintentional, dangerous, or just a waste of time for the program) things like:
Your assignment operator will be written: