Recently I posted a piece of my code here and got a comment (unrelated to the original question) that using this
for all member functions and attributes of a class is "not simply a matter of personal coding style, it is bad practice". Unfortunately, the person refused to elaborate and told me to look it up myself.
I have used Google a bunch (but it's really hard looking up anything with "this" as a keyword), and looked around here, but I only found some examples of when this
has to be used.
I know the situations where using this
is unavoidable (parameter / variable with the same name, template inheritance etc.), but in time I started using this
wherever possible because I can find my way around my code easier and faster. My reasons include:
- quick check if the function
f
should be a member function at all: if there is nothis
in the code, it can be taken out of the class - quick check if
f
can be aconst
function: if nothis
on the left side, most probably can be madeconst
(not always but I find it useful when skimming) - quick check if the object is "changing" itself in a "predefined" way in
f
, or if it's a composite member function (a member method called withthis
vs. an "outside" algorithm operating on the object without this) - debugging; i.e. if a member attribute gets assigned the wrong value at any point, I have to concentrate on the lines containing
this
to find the problem, as other lines do not change the object
Frankly, the comment about this being "bad practice" rattled me a bit. But, one comment in itself does not mean much, so I would like to ask is there anything inherently bad with using this
consistently for all member functions and attributes? If so, what are the major drawbacks that put it past a (possibly clumsy, unpopular or not-widespread) personal style, and place it in the "bad practice" category?