4.4 What Is the this Pointer?
We must implement a copy() member function that initializes one Triangular class object with another. For example, given
Triangular tr1( 8 );
Triangular tr2( 8, 9 );
the invocation of
tr1.copy( tr2);
assigns tr1 the length and beginning position of tr2. In addition, copy() must return the class object that is the target of the copy. In our example, tr1 is both the target and the object that must be returned. How can we do that? For example, here is an implementation of copy():
Triangular& Triangular::
copy( const Triangular &rhs )
{
_length = rhs._length;
_beg_pos = rhs._beg.pos;
_next = rhs._beg_pos-1;
return ??? what exactly ???;
};
rhs is bound to tr2 in our example. In the assignment
_length = rhs._length;
_length refers to the member associated with tr1. We need a way of referring to the tr1 class object as a whole.
The this pointer provides us with that handle.
Within a member function, the this pointer addresses the class object that invokes the member function. In our example, tr1 is addressed by the this pointer. How does that get done? Internally, the compiler adds the this pointer as an argument to each class member function. copy(), for example, is transformed as follows:
// Pseudo Code: Internal Member Function Transformation
Triangular& Triangular::
copy( Triangular *this, const Triangular &rhs )
{
this->_length = rhs._length;
this->_beg_pos = rhs._beg.pos;
this->_next = rhs._beg_pos-1;
};
This transformation requires a second transformation: Each invocation of copy() must now provide two arguments. To accomplish this, our original invocation
tr1.copy( tr2);
is internally transformed into
// internal code transformation:
// tr1 becomes the class object addressed by the this pointer
copy( &tr1, tr2);
Inside a class member function, the this pointer provides access to the class object through which the member function is invoked. To return tr1 from within copy(), we simply dereference the this pointer as follows:
// returns the class object addressed by the this pointer
return *this;
When you copy one class object with another, it is a good practice to first check to make sure that the two class objects are not the same. To do this, we again use the this pointer:
Triangular& Triangular::
copy( const Triangular &rhs )
{
// check that the two objects are not the same
if ( this != &rhs )
{
_length = rhs._length;
_beg_pos = rhs._beg_pos;
_next = rhs._beg_pos-1;
}
return *this;
}
|