Pointers to Class Members with Pointers to Objects


#include <iostream.h>
/*----------------------Class Interfaces-------------------------*/
class A
{
        int a1;                    // private data member
    public :
        int a2;                    // public data member

        A(int, int);
        void display_a1a2();
};
/*----------------------Class Implementations---------------------*/
// member function definitions for class A
A::A(int x, int y)
{
    a1 = x;
    a2 = y;
}
void A::display_a1a2()
{
    cout << "a1 = " << a1 << "\n";
    cout << "a2 = " << a2 << "\n";
}
/*----------------------Class definitions ends here---------------*/
void main(void)
{
    int A::*ip;         // declaration of pointer to data member
                            // of class 'A'
    void (A::*fp)();    // declaration of pointer to member function
                            // of class 'A'
    A obj(12,14), *p;
    p = &obj;                // pointer to object assigned
    ip = &A::a2;         // pointers to class members assigned
    fp = &A::display_a1a2;
    p->*ip = 15;        // modified object's data member through pointer
    (p->*fp)();        // call to member function through pointer
}

0 comments:

Post a Comment

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|