Understanding the usefulness and behviors of 'this' pointer

I am a student at the University of Advancing Technology in Tempe, AZ. As a part of our assignment for this week, I am to inquire this forum with a question. I presented the following code snippet in a class discussion regarding keyword 'this', based on my understanding of it and in an attempt to simplify how it works:

class Test {

public:
//Accessor
int fun() {
return this->data;
}

private:
int data = 0;

}

I had two questions about 'this':
1. In what situation would using 'this' be handy when compared to other methods? How does it provide the same advantages of using a standard pointer?

2. It is my understanding that the address of 'this' is passed as a hidden parameter. Is this done when the object is instantiated or when a function is called?

These are genuine questions that I hope to get answered just in case I'm missing out on something by having never used 'this'. Given this, any other tidbits would be appreciated. Thanks for the help!
The "this" pointer allows you to access the instance of the class whose method is being called. Since every instance of Test has a member data, you need a way to have the method access the members of that particular instance.

From this you can draw that the "this" parameter is passed when you call the method.
the this pointer has the direction of your object.
1
2
3
int Test::fun(){
  return data; //no need to use 'this'
}

I don't understand your first question.
As I understand it, when you call a member function, the object calling that function has its address passed by reference - you can access it with the word 'this'. However, in those functions, it's assumed that unspecified references to class parameters (in your example, data) are intended to act upon the object calling the function ('this').

Topic archived. No new replies allowed.