The this Pointer


The concept of reentrant code existed long before the development of the C++ Language. Classes with only non-static members, and whose methods access only members within the class and automatic variables are reentrant !

The basic concept behind code reentrancy is that a single body of code can be executed simultaneously on different sets of data. This is precisely what is achievable using a C++ class. Each instance of a C++ class has its own data upon which the methods act (static data excluded). To achieve this, a 'hidden' pointer to the class instance data is passed to each non-static method of the class upon its invocation. For an arbitrary class X, the keyword this is available to non-static methods of the class, and is a pointer to the instance of X for which the method was invoked. The type of the this pointer depends upon type of the method (of class X). This dependency may be described as follows:

The following restrictions also apply:

Example

class point
{
 public:
  point(int x_set=0, int y_set=0) : x(x_set), y(y_set) {} // Default Constructor
 
  point(const point& copy) : x(copy.x), y(copy.y) {}      // Copy Constructor
   
 
  point& operator=(const point& assign)        // Assignment Operator
  {x = assign.x; y = assign.y; return *this;}  // Note: type of this pointer is point* const,
                                               // and when the this pointer is dereferenced
                                               // it may be used to initialize the returned reference
 
  void set(int x_set, int y_set) const // Note that point::set is constant
  {x = x_set;y = y_set;}               // so these assignments are syntax errors !!!
 
  int& operator()(int index) {return index ? x : y;} // matrix like access to members
 
 private:
  int x;
  int y;
};
 
point point_a(1,2);
point point_b(point_a = point(3,4)); // Calls assignment operator first, then copy constructor
                                     // Only possible because assignment operator returns *this
 
void f(const point& point_increment) // Note - reference to constant instance of point as parameter
{
 point_increment(0)++;               // Syntax Error !!! point::operator()
 point_increment(1)++;               // is non-constant so can't be called for constant instance
}