Should I use `this` within a class?

Ben picture Ben · Mar 6, 2012 · Viewed 29.5k times · Source

Within a member function of a class in C++, does it make a difference, if I use this->dataMember or just dataMember? What is considered better style? Is there any performance difference?

(I am not talking about the case where a local variable has the same name as the data member, in which case you must, to my knowledge, use this-> to distinguish between them.)

Answer

James Kanze picture James Kanze · Mar 6, 2012

As a general rule, it's a question of local conventions. Most of the places I've seen do not use this-> except when necessary, and that's the convention I prefer as well, but I've heard of people who prefer to use it systematically.

There are two cases when it is necessary. The first is if you've hidden the name with the same name in local scope; if e.g. you have a member named toto, and you also named your function argument toto. Many coding conventions mark either the member or argments to avoid this case, e.g. all member names start with my or m_, or a parameter name will start with the.

The other case is that this-> can be used in a template to make a name dependent. This is relevant if a template class inherits from a dependent type, and you want to access a member of the base, e.g.:

template <typename T>
class Toto : public T
{
public:
    int f()
    {
        return this->g();
    }
};

Without the this-> here, g() would be a non-dependent name, and the compiler would look it up in the context of the template definition, without taking the base class into consideration.