+ 2

What does "this->" means in c++...

.

25th Aug 2018, 10:09 AM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
2 Respuestas
+ 7
The "this" keyword returns a pointer which points to the current instance of a class. The "->" operator is used to invoke class members using a pointer (which points to an instance of a class). class A { public: int n; void setN(int n) { this->n = n; // Assign value of parameter n to class member n } }; What happens if you do n = n; instead of this->n = n; ? The program would assign the value of the parameter back to itself, instead of assigning it to the n which is local to the class. Of course, you can name the parameter as something else, which would make it unnecessary to use the "this" pointer. I'm just showing how it affects things. https://www.sololearn.com/learn/CPlusPlus/1900/?ref=app
25th Aug 2018, 10:17 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
The this keyword is a special pointer that is used to refer to the current object of the class. Now, since its a pointer, you need to dereference the pointer to access the method/member, or just use -> which dereferences it internally. Eg : void print() { cout<<"Hello"; } class A { int var; public: void print() { cout<<this->var; // You can also do *this.var; } void set(int v) { var=v; this->print(); } }; Now in the class above, if you left out the this-> in the set() method, the compiler may assume that you attempted to use the global print(), and throw an ambiguity error. 'This' solves the error.
25th Aug 2018, 10:23 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar