Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of this->

Tags:

java

c++

this

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.

like image 834
Sim Avatar asked Dec 06 '22 18:12

Sim


1 Answers

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.

like image 150
James Kanze Avatar answered Dec 22 '22 10:12

James Kanze