17

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_Learner
  • 589
  • 1
  • 6
  • 16
Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179

16 Answers16

42

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.

sth
  • 222,467
  • 53
  • 283
  • 367
31

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.

drby
  • 2,619
  • 25
  • 26
9

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!

Andy Dent
  • 17,578
  • 6
  • 88
  • 115
  • 3
    Nobody seems to be mentioning that another way of resolving member names is by using the http://en.wikipedia.org/wiki/Scope_resolution_operator. E.g. Classx::doSomething(); – Rehno Lindeque Dec 02 '09 at 11:57
  • 10
    If applied to a function it has the effect of guaranteeing which version of a possibly virtual function is invoked, preventing polymorphism and commonly used to call a parent of an overriden function. It is NOT a safe equivalent of this->doSomething(). – Andy Dent Dec 03 '09 at 11:30
  • 2
    That's true, I'd forgotten about this case! Thanks Andy. – Rehno Lindeque Dec 03 '09 at 14:23
5

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).

peterchen
  • 40,917
  • 20
  • 104
  • 186
  • 4
    I disagree that this is necessarily a bad practice. If you have a good, clear, and umbiguous name for an object or variable... why change it? – TK. Feb 23 '09 at 11:14
  • IMO coding standard should make public properties vs. internal members vs. local variables/parameters unambigous. As much as i hate typing `m_`, there is a good reason for it. – peterchen Feb 23 '09 at 11:31
  • To clarify: I think it's ok when it happens, but when it happens often, you likely have a readability problem and an invitation to attention slip bugs. Now, your standard might declare 'this->' to be used always as 'the distinguisher', but I don't think that's a good choice. – peterchen Feb 23 '09 at 11:59
2

There are many good answers, but none of them mention that using this-> in source code makes it easier to read, especially when you are reading a code of some long function, but even a short function, imagine a code:

bool Class::Foo()
{
    return SomeValue;
}

from looking on this code, you can't clearly know what SomeValue is. It could be even some #define, or static variable, but if you write

bool Class::Foo()
{
    return this->SomeValue;
}

you clearly know that SomeValue is a non-static member variable of the same class.

So it doesn't just help you to ensure that name of your functions or variables wouldn't conflict with some other names, but it also makes it easier for others to read and understand the source code, writing a self documenting source code is sometimes very important as well.

Petr
  • 13,747
  • 20
  • 89
  • 144
2

Another case, that has arrived on the scenes after C++11 is in lambdas where this is captured.

You may have something like:

class Example
{
  int x;
public:
  std::function<void()> getIncrementor()
  {
    return [this] () -> void
    {
      ++(this->x);
    }
  }
};

Although your lambda is generated within a class, it will only have access to local variables by capturing them (if your compiler does C++14) or capturing this. In the second case, inside the body of lambda, there simply is not x, but only this->x.

v010dya
  • 5,296
  • 7
  • 28
  • 48
2

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

Edouard A.
  • 6,100
  • 26
  • 31
2

I think it is mainly as an aid to the reader. It makes it explicit that what is being called is a method on the object, and not an ordinary function. When reading code, it can be helpful to know that the called function can change fields in the current object, for instance.

unwind
  • 391,730
  • 64
  • 469
  • 606
2

It's your own choice. I find it more clear when you use this. But if you don't like it, you can ommit it.

Ikke
  • 99,403
  • 23
  • 97
  • 120
2

This is really a matter of style and applies to many other languages such as Java and C#. Some people prefer to see the explicit this (or self, or Me, or whatever) and others do not. Just go with whatever is in your style guidelines, and if it's your project, you get to decide the guidelines.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
2

This is done to be explicit about the fact that the variable being used is a member variable as opposed to a local or global variable. It's not necessary in most cases, but being explicit about the scope could be helpful if you've trumped the variable with a declaration of the same name in a tighter scope.

At companies I've worked at, we just prepended "m_" to member variables. It can be helpful sometimes, and I much prefer it to using "this->".

Edit: Adding a link to the GCC docs, which explain a case where using this-> is necessary to get a non-dependent lookup to work correctly.

Dan Olson
  • 22,849
  • 4
  • 42
  • 56
1

I don't think it makes a difference to the compiler, but I always write this-> because I believe it makes the code self-documenting.

Ray Hidayat
  • 16,055
  • 4
  • 37
  • 43
1

Disambiguation: in case you have another similar naming function/variable in the same namespace? I've never seen usage for any other reason.

dirkgently
  • 108,024
  • 16
  • 131
  • 187
1

I prefer it without the explicit this pointer as well. For method calls it doesn't add a lot of value, but it helps distinguish local variables from member variables.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
1

I can't quite remember the exact circumstances, but I've seen (very rare) instances where I had to write "this->membername" to successfully compile the code with GCC. All that I remember is that it was not in relation to ambiguity and therefore took me a while to figure out the solution. The same code compiled fine without using this-> in Visual Studio.

Adrian Grigore
  • 33,034
  • 36
  • 130
  • 210
  • It has to do with dependent template parameters, this link gives a good explanation: http://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html – Dan Olson Feb 24 '09 at 19:57
0

I will use it to call operators implicitly (the return and parameter types below are just dummies for making up the code).

struct F {
  void operator[](int); 
  void operator()();

  void f() {
    (*this)[n];
    (*this)();
  }

  void g() {
    operator[](n);
    operator()();
  }
};

I do like the *this syntax more. It has a slightly different semantic, in that using *this will not hide non-member operator functions with the same name as a member, though.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
  • What do you mean "`*this` will not hide non-member operator functions with the same name as a member"? Can you provide an example? – rlbond Dec 09 '09 at 22:29
  • Example: `struct A { void operator*(); void f(); }; void operator*(A, A); void A::f() { A a; operator*(a, a); }` <- this is ill-formed, as the member operator* hides the global operator*. But if you write `a * a` (the expression syntax), it will work fine, as lookup will be separate for members and nonmembers. – Johannes Schaub - litb Dec 09 '09 at 22:41