Archived

This topic is now archived and is closed to further replies.

"this" POINTER?

This topic is 5401 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In C++ all instances of a class or struct have a this pointer which points to themselves, which is useful if it wants to pass itself to another function or, in the case of operator overloading, return a reference to itself.

Share this post


Link to post
Share on other sites
The this pointer is a pointer to the current instance of a class or struct.
You will only see the "this" pointer used inside of a member function. Its common to use "this" in when overriding operators because many times you are operating doing operations on the current class/struct.

Here is a common example

    
Vector& Vector::operator*=(const float fScalar)
{
m_fX *= fScalar;
m_fY *= fScalar;
m_fZ *= fScalar;
return *this;
}

Vector Vector::operator*(const float fScalar) const
{
return Vector (*this)*=fScalar;
}





Journal

[edited by - Garrland on March 4, 2003 12:32:28 PM]

Share this post


Link to post
Share on other sites
Why I have to return a reference to the this pointer instead of the pointer.

I have to do this:


    
Counter& Counter::operator++()
{
++itsVal;
return *this;
}


Why I cant do this:


  
Counter* Counter::operator++()
{
++itsVal;
return this;
}


[edited by - tolueno on March 4, 2003 12:54:46 PM]

[edited by - tolueno on March 4, 2003 12:55:57 PM]

Share this post


Link to post
Share on other sites