Is there any reason to use this->

I am programming in C++ for many years, still I have doubt about one thing. In many places in other people code I see something like:

void Classx::memberfunction()
{
    this->doSomething();
}

If I need to import/use that code, I simply remove the this-> part, and I have never seen anything broken or having some side-effects.

void Classx::memberfunction()
{
    doSomething();
}

So, do you know of any reason to use such construct?

EDIT: Please note that I'm talking about member functions here, not variables. I understand it can be used when you want to make a distinction between a member variable and function parameter.

EDIT: apparent duplicate: Are there any reasons not to use "this" ("Self", "Me", ...)?


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.


If there is another variable in the same scope with the same name, the this-> will remove the ambiguity.

void Bar::setFoo(int foo)
{
    this->foo = foo;
}

Also it makes it clear that you're refering to a member variable / function.


To guarantee you trigger compiler errors if there is a macro that might be defined with the same name as your member function and you're not certain if it has been reliably undefined.

No kidding, I'm pretty sure I've had to do exactly this for that reason!


As "code reason", to distinguish a local parameter or value (that takes precedence) from a member:

class Foo
{
    int member;
    void SetMember(int member)
    {
       this->member = member;
    }
}

However, that's bad practive to begin with, and usually can be solved locally.

The second reason is more "environment": it sometimes helps Intellisense to filter what I am really looking for. However, I also thing when I use this to find the member I am looking for I should also remove this.

So yes, there are good reasons, but they are all temporary (and bad on the long run).


I can think of readability like when you use additional parenthesis to make things clear.