Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason to use this->

Tags:

c++

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", ...)?

like image 484
Milan Babuškov Avatar asked Feb 23 '09 11:02

Milan Babuškov


3 Answers

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.

like image 176
sth Avatar answered Oct 07 '22 05:10

sth


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.

like image 40
drby Avatar answered Oct 07 '22 07:10

drby


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!

like image 9
Andy Dent Avatar answered Oct 07 '22 05:10

Andy Dent