+ 1

Question about this. / this-> c++

Hi. Before I see that there Is no error In code I think we must use construction this.x or this->x In class methods to have access In fields and code will not work correctly without It. But It’s ok. The question Is for what we should use this In general? Only If we use same variable name In function like in field? https://code.sololearn.com/c0fofxzT7Nul/?ref=app

7th Jul 2019, 10:08 AM
Chicherin Alexey
Chicherin Alexey - avatar
2 Respuestas
+ 3
The this keyword is usually used to resolve ambiguity in cases where the variable names are same. Since it is a pointer to the current class object, you need to use the pointer to member (->) or the arrow operator to access the members and methods (this->x for example. this->x is actually equivalent to (*this).x). As for other uses, you might need 'this' when you need to return the current object in a member or operator, such as the in the assignment operator, which is supposed to return a reference to the current object. class A { A& operator=(const A& obj) { /* Assign data */ return *this; } }; int main() { A a1, a2, a3; A a4; a1 = a2 = a3 = a4; } Now if the assignment operator returned void, the multiple assignment would not work. The return value of a3 = a4 is assigned to a2 and then to a1. This way a1, a2, a3, and a4 all contain the same data. Also, 'this' can be used to call copy constructors or call methods and functions that require an object of the class.
7th Jul 2019, 10:45 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 3
this -> is used to reference general objects of the same class, like in the constructor, as the constructor will run for every object of the class, we use this to say something for "this" object of the class. It's also used in the deconstructor for the same reason.
7th Jul 2019, 10:41 AM
alvaro.pkg.tar.zst
alvaro.pkg.tar.zst - avatar