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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With