Example of Pointers to Members


/************************************************************************
*

Pointers to members can be declared and used as shown in the following example:

                                                                        *
************************************************************************/


// This example illustrates pointers to members.

#include <iostream.h>
class X
{
public:
      int a;
      void f(int b)
      {
             cout << "The value of b is "<< b << endl;
      }
};
//      .
//      .
//      .
void main ()
{
      // declare pointer to data member
      int X::*ptiptr = &X::a;

      // declare a pointer to member function
      void (X::* ptfptr) (int) = &X::f;

      X xobject;                  // create an object of class type X
      xobject.*ptiptr = 10;       // initialize data member

      cout << "The value of a is " << xobject.*ptiptr << endl;
      (xobject.*ptfptr) (20);     // call member function
}


/************************************************************************
*

The output for this example is:

The value of a is 10
The value of b is 20


                                                                        *
************************************************************************/