Search code examples
c++classpointersthisthis-pointer

Is it okay to use the this pointer?


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?


Solution

  • 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.