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.