"this" POINTER?
Can somebody tell me what this-Pointer is used for?
And why is used only with references and overloading operators?
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.
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
Journal
[edited by - Garrland on March 4, 2003 12:32:28 PM]
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]
Why I have to return a reference to the this pointer instead of the pointer.
I have to do this:
Why I cant do this:
[edited by - tolueno on March 4, 2003 12:54:46 PM]
[edited by - tolueno on March 4, 2003 12:55:57 PM]
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]
Because then you''d have to dereference the result of the ++ operator which would lead to ugly syntax.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement