Using the this Pointer to Avoid Naming Collisions

Member functions use the this pointer implicitly (as we’ve done so far) or explicitly to reference an object’s data members and other member functions. A common explicit use of the this pointer is to avoid naming conflicts between a class’s data members and member-function parameters (or other local variables). Consider the Time class’s hour data member and setHour member function in Figs. 9.49.5. We could have defined setHour as:

// set hour valuevoid Time::setHour( int hour ){   if ( hour >= 0 && hour < 24 )      this->hour = hour; // use this pointer to access data member    else      throw invalid_argument( "hour must be 0-23" );} // end function setHour

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.