class myObj {
myObj* getPointer() {
return(this); //returns a pointer to the current object instance
}
}
int main() {
myObj m();
myObj* p_m;
p_m=m.getPointer;
}
The this pointer always points to the object that is being used to call the function. Consider the situation:
1 2 3 4 5 6 7 8 9 10 11 12 13
class Example
{
int data;
public:
Example(int data);
~Example();
}
Example::Example(int data)
{
// by using "this", we can avoid confusion
this->data = data;
}
class C
{
public:
void func()
{
cout << this << endl;
}
};
int main()
{
C a, b;
a.func(); // prints the address of a
cout << &a << endl; // has matching output with above
// since func() was called on object 'a', this will point to 'a' inside the function
b.func(); // prints the address of b
cout << &b << endl; // matches b.func()'s output
// this time, since func() was called on object 'b', this points to 'b'
}
@OP: The other posters here have covered the basics of what the keyword this does, and as you can see is of very limited use to a beginner programmer. But now how about a more practical, albeit more complicated example?
Let's say you want to create an object that helps you manage your Windows without having to bounce all over the API. There is a structure in Windows called "STARTUPINFO" that holds some pretty useful information and you would like to include that information in your object (this is just an example, you can do this with almost any API or object). Now the obvious answer might be to just include an instance of that structure in your object, but that means you would have to refer to that struct within your own object in order to use any of those properties. The solution to this is simple, you just have your object inherit from the STARTUPINFO struct. But then how do you use the "GetStartupInfo()" function to fill in all of this data if you can't refer to the object? The answer is Polymorphism, because your object is now a child of the struct "STARTUPINFO" you can treat a pointer to your object as a pointer to it's parent. This means that passing a reference to your object with the keyword this in your objects constructor will fill in the attributes inherited from the STARTUPINFO struct. To illustrate:
Now because this example is a console program a lot of the attributes don't exist so they won't be filled in but you can see that the example that I used 'lpTitle' will match the text in the title bar of the window. Although this may be more of an example of how Polymorphism works, it would not be possible without the keyword "this".