views:

277

answers:

6

Possible Duplicates:
Is excessive use of this in C++ a code smell

Given that most organizations have a coding standard for member variables like "m_memberVar" or "memberVar_", are there good reasons to use "this->memberVal" format instead?

Is there any reason not to?

A: 

The main reason not to include 'this' everywhere is simply to avoid clutter. An access to a variable that's NOT a member variable should be rare in a good object-oriented design.

I. J. Kennedy
What about for (int i=0; i<100; ++i)? Accessing "i" is perfectly common and accepted design.
sharth
@sharth: proper OO people don't use explicit loops, and shudder in horror at the thought of integer *loop counters*. There should be *at least* one interface between the code you write and the code that actually does something...
Shog9
@Shog9: Your last statement can be interpreted recursively (and will cause a stack overflow, or infinite loop, in case of tail call optimization ;))
Mehrdad Afshari
I meant besides local variables.
I. J. Kennedy
+5  A: 

Technically I don't think there is any drawback. What is more important, like with any coding style - is that all developers need to follow it. It is really messy when there is a mixture of m_memberVar, memberVar_ and this-> in the code.

Anders K.
A: 

I think it is a much more better looking choice then having a _ in front of every variable. But with having a good IDE none of the both choices are needed any and should only be used to make something more clear.

Janusz
A: 

In my experiences, I typically use the "this" keyword for variables in constructors and setters. It cleans up the assignment of arguments, for example:

MyClass(int x) {
  this.x = x;
}

Just be careful not to do something like

MyClass(int x) {
  x = x;
}

as this assignment will have no effect. However, finalizing the x member variable will prevent this from happening (and most IDEs will tell you the assignment does nothing).

Most importantly (as another person also stated), consistency is important. Code written by one developer in your organization should look the same as code written by the other developers.

Jeff Storey
Your example is better done as `MyClass(int x) : x(x) {}` anyway.
greyfade
it was pseudocode. wasn't aiming for correct syntax (I'm a Java programmer)
Jeff Storey
A: 

I think is bad to use this->.
The code this->aMemberVariable and aMemberVariable is server same access in a object.
Use of this-> only adds more coding (typing) and makes the code look messy.

suprit chaudhary
A: 

I think using `this' keyword in C++ is a waste of space considering the language doesn't force you to do it and the fact that its almost never necessary, except maybe in constructors. If you can't keep track of the variables in a class, then the class is too big.