"this" POINTER?

Started by
3 comments, last by tolueno 21 years, 1 month ago
Can somebody tell me what this-Pointer is used for? And why is used only with references and overloading operators?
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.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.
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]
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]
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