I've only needed the this pointer on rare occasions. Here's an example (but shortened):
Suppose you have a Contour class that contains a linked list of data points and pointers to previous and next contours. Something like this:
-
class Contour{
-
private:
-
DataPoint* pFirstDataPoint;
-
bool IsClosed;
-
Contour* pPreviousContour;
-
Contour* pNextContour;
-
public:
-
Contour();
-
~Contour();
-
bool CleanContour( void );
-
// etc
-
};
-
Suppose that you want the CleanContour() function to remove all contours prior to and after the object, but not the object. Then you might do something like this:
-
bool Contour::CleanContour( void )
-
{
-
Contour* pCurrentContour = this;
-
// find the "first" contour
-
while( pCurrentContour->pPreviousContour )
-
{ pCurrentContour = pCurrentContour->pPreviousContour; }
-
-
// delete all contours but this one
-
-
while( pCurrentContour )
-
{
-
Contour* pTemp = pCurrentContour->pNextContour;
-
if( pCurrentContour != this )
-
{ delete pCurrentContour; }
-
pCurrentContour = pTemp;
-
}
-
pPreviousContour = NULL;
-
pNextContour = NULL;
-
return true;
-
}
-
So, what's going on here is that we're first going as far back along the linked list as we can, then progressing forward and deleting everything, taking care to not delete our current object.
Yes, this could have been done differently without this "this" pointer. (Delete backward, then delete forward.) However, there are cases where the "this" keyword is helpful for identifying when you've reached the current object, and this illustrates how to use it.
Another potential use: print out "this" as part of an error message to identify the memory address of an object that causes an error.
I hope this is somewhat helpful. -- Paul