Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use the this pointer? [duplicate]

Possible Duplicates:
Is there any reason to use this->
When should this-> be used?
When should I make explicit use of the this pointer?

When working with pointers to classes, I like to add a this-> in front of variables in a class to make it clearer that the variable I'm talking about is in the current class, as opposed to temporary variables, etc. So my lines would be something like

if(this->thing > other->thing)
    this->doFoo();

Instead of

if(thing > other->thing)
    doFoo();

Is it okay to add the superfluous this, or would that degrade code readability?

like image 588
wrongusername Avatar asked Dec 12 '22 16:12

wrongusername


2 Answers

Consistency consistency consistency.

I conisder the this-> prefix a valid coding style if you use it throughout your entire project everywhere a member is accessed.

I prefer using a signifying prefix for members, e.g. m_. I feel it is less cutter and less tag soup than the explicit this->:

(alpha-this->gamma > this->alpha-gamma)

vs.

(alpha-m_gamma > m_alpha-gamma)

(The dotNetties have labeled m_ outdated - I use it on small C# projects out of spite. but anyway, any other distinct prefix would do, too.)

I've seen it used often to help intellisense get in gear, or to specifically filter members - which is ok, though leaving it in for that reason is questionable, especially if not used consistently.

like image 103
peterchen Avatar answered Dec 15 '22 05:12

peterchen


That depends on your coding style, however many people would use

_myVariable
m_myVariable
myVariable_

To differentiate member variables from the other.

But the most important thing is to just be consistent

like image 44
kshahar Avatar answered Dec 15 '22 05:12

kshahar