When should I make explicit use of the `this` pointer?

When should I explicitly write this->member in a method of a class?


Usually, you do not have to, this-> is implied.

Sometimes, there is a name ambiguity, where it can be used to disambiguate class members and local variables. However, here is a completely different case where this-> is explicitly required.

Consider the following code:

template<class T>
struct A {
   int i;
};

template<class T>
struct B : A<T> {

    int foo() {
        return this->i;
    }

};

int main() {
    B<int> b;
    b.foo();
}

If you omit this->, the compiler does not know how to treat i, since it may or may not exist in all instantiations of A. In order to tell it that i is indeed a member of A<T>, for any T, the this-> prefix is required.

Note: it is possible to still omit this-> prefix by using:

template<class T>
struct B : A<T> {

    using A<T>::i; // explicitly refer to a variable in the base class

    int foo() {
        return i; // i is now known to exist
    }

};

If you declare a local variable in a method with the same name as an existing member, you will have to use this->var to access the class member instead of the local variable.

#include <iostream>
using namespace std;
class A
{
    public:
        int a;

        void f() {
            a = 4;
            int a = 5;
            cout << a << endl;
            cout << this->a << endl;
        }
};

int main()
{
    A a;
    a.f();
}

prints:

5
4