Friday, 9 May 2014

Pointer To Member Operators

The pointer-to-member operators ->* and .* group left-to-right

Example of Pointer to Member Operators:



Example1: Pointer to member data
#include<cstdio>
class Test
{
public:
        int x;
        Test():x(5){}
        void display()
        {
                printf("x:%d\n",x);
        }
};
int main()
{
        Test obj;
        Test *objPtr=&obj;         //pointer to object "obj"
        int Test::*p = &Test::x;  //p is a pointer to member x of Test.
        obj.display();            // output:5
        obj.*p=7;                 //modify the content of x by using pointer p
        obj.display();            // output:7
        objPtr->*p=10;            //modify the content of x by using pointer p accessed by a pointer points to an object "obj".
        obj.display();            // output:10
}

Example2: Pointer to member function
#include<cstdio>
class Test
{
public:
        int x;
        Test():x(5){}
        void display()
        {
                printf("x:%d\n",x);
        }
};
int main()
{
        Test obj;
        Test *objPtr=&obj;                   //pointer to object "obj"
        void (Test::*ptr_display)();
        ptr_display = &Test::display;
        obj.display();                      //calling display function by object
        (obj.*ptr_display)();            //calling display function by pointer to member function
        (objPtr->*ptr_display)();           //calling display function by pointer to member function using object pointer
}

No comments :

Post a Comment