Is there any reason to use this->

The only place where it really makes a difference is in templates in derived classes:

template<typename T>
class A {
protected:
  T x;
};

template<typename T>
class B : A<T> {
public:
  T get() {
    return this->x;
  }
};

Due to details in the name lookup in C++ compilers, it has to be made explicitly clear that x is a (inherited) member of the class, most easily done with this->x. But this is a rather esoteric case, if you don’t have templated class hierarchies you don’t really need to explicitly use this to access members of a class.

Leave a Comment