Pointers to Class Members with .* and ->*, pointer-to-class-member operators. - C++ Class

C++ examples for Class:Member Function

Description

Pointers to Class Members with .* and ->*, pointer-to-class-member operators.

Demo Code

#include <iostream> 
using namespace std; 

class Test { /*from  w w  w .  j a  va2s . co m*/
public: 
   void func() { 
       cout << "In func\n"; 
   }

   int value; // public data member 
};

void arrowStar( Test * ); // prototype 
void dotStar( Test * ); // prototype 

int main() 
{ 
   Test test; 
   test.value = 8; // assign value 8 
   arrowStar( &test ); // pass address to arrowStar 
   dotStar( &test ); // pass address to dotStar 
}

// access member function of Test object using ->* 
void arrowStar( Test *testPtr ) 
{ 
   void ( Test::*memberPtr )() = &Test ::func; // declare function pointer 
    ( testPtr->*memberPtr )(); // invoke function indirectly 
}

// access members of Test object data member using .* 
void dotStar( Test *testPtr2 ) 
{ 
   int Test ::*vPtr = &Test::value; // declare pointer 
   cout << ( *testPtr2 ).*vPtr << endl; // access value 
}

Result


Related Tutorials