Possible Duplicate:
Is excessive use of this in C++ a code smell
When should you use the "this" keyword in C++?
Is there any reason to use this->
In C++, is the keyword this
usually omitted? For example:
Person::Person(int age) { _age = age; }
As opposed to:
Person::Person(int age) { this->_age = age; }
There can be 3 main usage of this keyword in C++. It can be used to pass current object as a parameter to another method. It can be used to refer current class instance variable. It can be used to declare indexers.
In C you do not have the this keyword. Only in C++ and in a class, so your code is C and you use your this variable as a local method parameter, where you access the array struct.
While this is a totally subjective question, I think the general C++ community prefers not to have this-> . Its cluttering, and entirely not needed. Some people use it to differentiate between member variables and parameters.
The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).
Yes, it is not required and is usually omitted. It might be required for accessing variables after they have been overridden in the scope though:
Person::Person() { int age; this->age = 1; }
Also, this:
Person::Person(int _age) { age = _age; }
It is pretty bad style; if you need an initializer with the same name use this notation:
Person::Person(int age) : age(age) {}
More info here: https://en.cppreference.com/w/cpp/language/initializer_list
It's programmer preference. Personally, I love using this
since it explicitly marks the object members. Of course the _
does the same thing (only when you follow the convention)
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