Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

this

People also ask

When and where is this pointer useful?

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

What does * In pointer mean?

In a declaration, it means it's a pointer to a pointer: int **x; // declare x as a pointer to a pointer to an int.


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


There are several reasons why you might need to use this pointer explicitly.

  • When you want to pass a reference to your object to some function.
  • When there is a locally declared object with the same name as the member object.
  • When you're trying to access members of dependent base classes.
  • Some people prefer the notation to visually disambiguate member accesses in their code.

Although I usually don't particular like it, I've seen others use this-> simply to get help from intellisense!


  1. Where a member variable would be hidden by a local variable
  2. If you just want to make it explictly clear that you are calling an instance method/variable


Some coding standards use approach (2) as they claim it makes the code easier to read.

Example:
Assume MyClass has a member variable called 'count'

void MyClass::DoSomeStuff(void)
{
   int count = 0;

   .....
   count++;
   this->count = count;
}