Jump to content
  • Advertisement

Archived

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

tolueno

"this" POINTER?

This topic is 5619 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

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
Advertisement
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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!