The this Pointer

The this pointer is a special pointer that is accessible to member functions. The this pointer points to the object for which the member function is called. (There is no this pointer accessible to static member functions. Static member functions are described in Chapter 6.)

When you call a member function for an object, the compiler assigns the address of the object to the this pointer and then calls the function. Every time a member function accesses one of the class's data members, it is implicitly using the this pointer.

For example, consider the following C++ code fragment, describing a member function definition and function call:

void Date::setMonth( int mn )

{

month = mn;

}

...

// Member function call

myDate.setMonth( 3 );

This is roughly equivalent to the following C fragment:

// C equivalent of C++ member function

void Date_setMonth( Date *const this, int mn )

{

this->month = mn;

}

...

// Function call

Date_setMonth( &myDate, 3 );

Notice that the type of this is Date * for member functions of Date; the type is different for member functions of other classes.

When you write a member function, it is legal to explicitly use the this pointer when accessing any members, though it is unnecessary. You can also use the expression *this to refer to the object for which the member function was called. Thus, in the following example, the three statements are equivalent:

void Date::month_display()

{

cout << month; // These three statements

cout << this->month; // do the same thing

cout << (*this).month;

}

A member object can use the this pointer to test whether an object passed as a parameter is the same object that the member function is called for. For example, the operator= function for the String class can be rewritten as follows:

void String::operator=( const String &other )

{

if( &other == this )

return;

delete buf;

length = other.length;

buf = new char[length + 1];

strcpy( buf, other.buf );

}

The function tests whether the address of the other object is equal to the value of the this pointer. If so, a self-assignment is being attempted, so the function exits without doing anything. Otherwise it performs the assignment normally.