Archived

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

tolueno

"this" POINTER?

Recommended Posts

Can somebody tell me what this-Pointer is used for? And why is used only with references and overloading operators?

Share this post


Link to post
Share on other sites
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
Because then you''d have to dereference the result of the ++ operator which would lead to ugly syntax.

Share this post


Link to post
Share on other sites