Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of "this" keyword in C++ [duplicate]

Tags:

c++

this

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; } 
like image 379
moteutsch Avatar asked Jul 21 '11 16:07

moteutsch


People also ask

What is the use of this keyword in C?

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.

Does C use this?

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.

Should you use this -> in C++?

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.

What is this keyword?

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).


Video Answer


2 Answers

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

like image 104
orlp Avatar answered Sep 27 '22 22:09

orlp


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)

like image 33
Rich Avatar answered Sep 27 '22 21:09

Rich