What is the proper use of the this
self-reference of a class?
I sometimes use it inside a method to clear out that the variable used is a member variable and not one declared inside the method, but on the other side I am wondering if this is a good reason to do so, as I think you should always code (and comment) in a way which is self-explaining and therefore would make such an unneeded use of this
unnecessary and another reason against it would be that you are actually producing more code than needed.
void function() {
while(i != this->length) //length is member var
/*do something*/
}
Another way of using it I frequently encounter is inside constructors (mostly in Java), as the parameters do have the same name as the member variables which has to be initialized. As the Primer states that this is bad code I am not doing this, but on the other side, I see how using the same name as the member-vars as parameter names clears out of which use they are.
C++
Constructor::Constructor(int size,int value) : this->size(size),
this->value(value) {};
Java
Constructor(int size,int value) {
this->size = size;
this->value = value;
}
I hope there is actually a rule considering both languages (Java/c++), if not I will retag for just c++ as this is the one I am more interested in.
For the most part, this->
is redundant. The exception is if you have a parameter or a local variable of the same name (easily, and probably best avoided), or in a template, in order to force the following symbol to be dependent—in this latter use, it is often unavoidable.
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