Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should this-> be used?

Tags:

c++

I was wondering if this-> should be used both:

void SomeClass::someFunc(int powder)
{
     this->powder = powder;
}

//and
void SomeClass::someFunc(bool enabled)
{
     this->isEnabled = enabled;
}

I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice.

Thanks

like image 395
jmasterx Avatar asked Dec 20 '10 15:12

jmasterx


2 Answers

this->

is needed when using the member directly would be ambiguous. This could happen with template code.

Consider this:

#include <iostream>

template <class T>
class Foo
{
   public:
      Foo() {}
   protected:
      void testing() { std::cout << ":D" << std::endl; }
};

template <class T>
class Bar : public Foo<T>
{
   public:
      void subtest() { testing(); }
};

int main()
{
   Bar<int> bar;
   bar.subtest();
}

This will fail since calling testing() is dependent on a template parameter. To say that you mean the function you will have to do this->testing(); or Foo<T>::testing();

Error message:

temp.cpp: In member function ‘void Bar<T>::subtest()’:
temp.cpp:16:32: error: there are no arguments to ‘testing’ that depend on a template parameter, so a declaration of ‘testing’ must be available [-fpermissive]
temp.cpp:16:32: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
like image 163
Maister Avatar answered Nov 15 '22 09:11

Maister


this is just a pointer to the object itself. It is made for readability, so that you know you're referencing to the object functions or variables, not something within the function.

I don't think there's any other good reason for it other than readability :-)

It's also good if you want to avoid ambiguous reference. Assume you have a global variable and a variable within the function that has the same name, then this-> would reference to the global variable.

like image 40
Jón Trausti Arason Avatar answered Nov 15 '22 09:11

Jón Trausti Arason