Use of "this" keyword in C++

C++This

C++ Problem Overview


> 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;
}

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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)

Solution 3 - C++

Either way works, but many places have coding standards in place that will guide the developer one way or the other. If such a policy is not in place, just follow your heart. One thing, though, it REALLY helps the readability of the code if you do use it. especially if you are not following a naming convention on class-level variable names.

Solution 4 - C++

this points to the object in whose member function it is reffered, so it is optional.

Solution 5 - C++

Yes. unless, there is an ambiguity.

Solution 6 - C++

For the example case above, it is usually omitted, yes. However, either way is syntactically correct.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmoteutschView Question on Stackoverflow
Solution 1 - C++orlpView Answer on Stackoverflow
Solution 2 - C++RichView Answer on Stackoverflow
Solution 3 - C++Muad'DibView Answer on Stackoverflow
Solution 4 - C++Alok SaveView Answer on Stackoverflow
Solution 5 - C++balkiView Answer on Stackoverflow
Solution 6 - C++ChadView Answer on Stackoverflow