Pointers to Class Members


#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
void 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);

    ip = &A::a2;        // pointers to class members assigned
    fp = &A::display_a1a2;

    obj.*ip = 15;    // modified object's data member through pointer

    (obj.*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|