0

My question refers to the case when I want to call other methods of the same class. Where's the difference of doing this with and without the use of 'this'? The same with variables of the class. Is there a difference accessing those variables through 'this'? Is it related to whether those methods / variables are private / public? Example:

class A {
private:
    int i;
    void print_i () { cout << i << endl; }

public:
    void do_something () {

        this->print_i();    //call with 'this', or ...
        print_i();          //... call without 'this'

        this->i = 5;        //same with setting the member;
        i = 5;
    }
};
newacct
  • 119,665
  • 29
  • 163
  • 224
a_guest
  • 34,165
  • 12
  • 64
  • 118

2 Answers2

1

There's no functional difference at all. But sometimes you need to explicitly include the this as a hint to the compiler; for example, if the function name is ambiguous on its own:

class C
{
   void f() {}

   void g()
   {
      int f = 3;
      this->f(); // "this" is needed here to disambiguate
   }
};

James Kanze's answer also explains a case where the explicit use of this changes which version of an overloaded name the compiler selects.

Community
  • 1
  • 1
dlf
  • 9,045
  • 4
  • 32
  • 58
1

Generally, it's a question of style. All of the places I've worked have preferred not using the this->, except when necessary.

There are cases where it makes a difference:

int func();

template <typename Base>
class Derived : public Base
{
    int f1() const
    {
        return func();      //  calls the global func, above.
    }
    int f2() const
    {
        return this->func();  //  calls a member function of Base
    }
};

In this case, this-> makes the name of the function dependent, which in turn defers binding to when the template is instantiated. Without the this->, the function name will be bound when the template is defined, without considering what might be in Base (since that isn't known when the template is defined).

James Kanze
  • 150,581
  • 18
  • 184
  • 329