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

Quick A: to disambiguate.

Recently on SO:

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

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
    }

};

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.