/////////////////////////////////////////////////////////////// // memptr.cpp - demonstrate use of pointers to members // // // // Jim Fawcett, CSE687 - Object Oriented Design, Spring 04 // /////////////////////////////////////////////////////////////// #include using namespace std; class C { public: // defining two overloaded functions void mf() { cout << "this is mf()" << endl; } int mf(int x) { cout << "this is mf(int x)" << endl; return 2*x; } }; int main () { cout << "\n\ntesting member pointers\n\n"; //---< ordinary pointers access any accessible member of specific object >--- C c; // an object C* cptr = &c; // ordinary pointer to object // - points to one specific object // - can use any accessible member // invoking each function through ordinary pointer to object cptr->mf(); int x = 1; int y = cptr->mf(x); cout << "result is: " << y << endl << endl; //----< member pointer accesses specific member of any instance >------------ void (C::*fptr)() = &C::mf; // fptr is pointer to member mf() // - points to specific member of any instance int (C::*gptr)(int) = &C::mf; // gptr is pointer to member mf(int) // - points to specific member of any instance (c.*fptr)(); // call mf() with obj & member ptr int z = (c.*gptr)(y); // call mf(y) with obj & member ptr cout << "result is: " << z << endl << endl; (cptr->*fptr)(); // call mf() with obj ptr & member ptr int w = (cptr->*gptr)(z); // call mf(z) with obj ptr & member ptr cout << "result is: " << w << endl << endl; return 0; }