Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The use case of 'this' pointer in C++

Tags:

c++

pointers

I understand the meaning of 'this', but I can't see the use case of it.

For the following example, I should teach the compiler if the parameter is the same as member variable, and I need this pointer.

#include <iostream>

using namespace std;

class AAA {
    int x;
public:
    int hello(int x) { this->x = x;}
    int hello2(int y) {x = y;} // same as this->x = y
    int getx() {return x;}
};

int main()
{
   AAA a;
   a.hello(10); // x <- 10
   cout << a.getx();
   a.hello2(20); // x <- 20
   cout << a.getx();
}

What would be the use case for 'this' pointer other than this (contrived) example?

Added

Thanks for all the answers. Even though I make orangeoctopus' answer as accepted one, it's just because he got the most vote. I must say that all the answers are pretty useful, and give me better understanding.

like image 318
prosseek Avatar asked Jul 23 '10 17:07

prosseek


2 Answers

Sometimes you want to return yourself from an operator, such as operator=

MyClass& operator=(const MyClass &rhs) {
     // assign rhs into myself

     return *this;
}
like image 109
Donald Miner Avatar answered Sep 22 '22 11:09

Donald Miner


The 'this' pointer is useful if a method of the class needs to pass the instance (this) to another function.

like image 28
Patrick Avatar answered Sep 24 '22 11:09

Patrick