-2

I have come across the following code but not able to understand what is the importance of the following concept . Please help .

#include <iostream>
using namespace std;

class cl 
{

public:
    cl(int i) { val=i; }
    int val;
    int double_val() { return val+val; }

};

int main()
{
    int cl::*data; // data member pointer
    int (cl::*func)(); // function member pointer
    cl ob1(1), ob2(2); // create objects
    cl *p1, *p2;
    p1 = &ob1; // access objects through a pointer
    p2 = &ob2;
    data = &cl::val; // get offset of val
    func = &cl::double_val; // get offset of double_val()
    cout << "Here are values: ";
    cout << p1->*data << " " << p2->*data << "\n";
    cout << "Here they are doubled: ";

    cout << (p1->*func)() << " ";
    cout << (p2->*func)() << "\n";
    return 0;
}
Viku
  • 2,845
  • 4
  • 35
  • 63

1 Answers1

4

Pointers-to-members are a special gadget in C++ that tell only tell you about a which member of a class you want without pertaining to any object. You need to combine a pointer-to-member with an object instance in order to obtain an actual member, whether it be a data or a function member.

Think of pointers-to-member as "offsets". Also, remember that pointers-to-member are not pointers!

We can rewrite your code to make it a bit clearer:

struct Foo
{
    int a;
    int b;
    double f(int, int);
    double g(int, int);
};

int main()
{
    int Foo::*ptm = &Foo::a;
    double (Foo::*ptmf)(int, int) = &Foo::f;

    Foo x, y, z;

    int numbers[] = { x.*ptm, y.*ptm, z.*ptm }; // array of Foo::a's

    ptm = &Foo::b;                              // reseat the PTM

    int more[] = { x.*ptm, y.*ptm, z.*ptm };    // array of Foo::b's


    double yetmore[] = { (x.*ptmf)(1,2), (y.*ptmf)(1,2) };

    ptmf = &Foo::g;

    double evenmore[] = { (x.*ptmf)(1,2), (y.*ptmf)(1,2) };
}

Note how we're using the pointers-to-member to refer only to the class member, and we can use that to get the same relative class member out of different objects.

(By contrast, we can also form a real pointer to an actual object member: int * p = &x.a;. That's because the member-int is actually an integer. But we cannot do anything analogous for member functions, because member functions are not functions (e.g. you cannot call them).)

Make sure you understand the difference between classes and objects, and this should become very clear!

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084