Who can tell more about the pointer this->. Here is a small piece of code:

#include <iostream> class thisis{ private: int var; public: thisis(int var) { this->var = var; std::cout << var; }; void getit() { std::cout << var; }; }; int main(){ thisis obj1(2); obj1.getit(); return 0; } 

Okay nothing complicated, the most common example from the book, we just made the assignment. which is equivalent to the usual assignment (only with one but, we have two variables of the same name and therefore we needed to rename one of them). just a pointer that works in a class. but the meaning of this pointer, maybe it has another use?

  • 2
    This is the old-fashioned syntax. In the constructor this practically not needed; Member initializer is more convenient: thisis(var): var(var) { std::cout << var; } thisis(var): var(var) { std::cout << var; } . The only known application to me is in assignment operators: return *this; - user58697
  • @ user58697 By the way, I forgot about overloading the assignment operator to mention - ParanoidPanda
  • I am funny sealed: не instead of мне - user58697

1 answer 1

In your example, you could do without the this pointer. For example,

 thisis(int var) { thisis::var = var; std::cout << var; }; 

If you need an example of another use of the this pointer, where you can't do without it, so here's an example.

 thisis & operator = ( const thisis &rhs ) { var = rhs.var; return *this; } 

Inside nonstatic functions that are members of a class, the this pointer points to the object for which the nonstatic function was called.

I already showed you an example of using this in the copy assignment operator. Sometimes in such statements it is required to check whether the object is assigned to itself.

Therefore, an assignment operator code might look like this.

 thisis & operator = ( const thisis &rhs ) { if ( this != &rhs ) { //... } return *this; }