c++this

When should I make explicit use of the this pointer?


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


Solution

  • 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 {
       T i;
    };
    
    template<class T>
    struct B : A<T> {
        T foo() {
            return this->i; //standard accepted by all compilers 
            //return i; //clang and gcc will fail
            //clang 13.1.6: use of undeclared identifier 'i'
            //gcc 11.3.0: 'i' was not declared in this scope
            //Microsoft C++ Compiler 2019 will accept it
        }
    
    };
    
    int main() {
        B<int> b;
        b.foo();
    }
    

    If you omit this->, some compilers do not know how to treat i. 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> {
        int foo() {
            return A<T>::i; // explicitly refer to a variable in the base class 
            //where 'i' is now known to exist
        }
    
    };