Use of "this" keyword in C++

moteutsch picture moteutsch · Jul 21, 2011 · Viewed 194.9k times · Source

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

Answer

orlp picture orlp · Jul 21, 2011

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