Monday, October 31, 2011

Pointers to Members in C++

Rarely used. Just keep a memo.

Example:
class A {
public:
    int x;
    char *s;
    void f( float );
};

int main()
{
    int A::*xp = &A::x;
    char *A::*sp = &A::s;
    void (A::*fp)(float) = &A::f;

    A a;
    A *ap = &a;

    a.*xp ...
    a.*sp ...
    (a.*)fp( 0.0 ) ...

    ap->*xp ...
    ap->*sp ...
    (ap->*)fp( 0.0 ) ...

    ...
    return 0;
}

Notes:
  1. Pointers to members cannot be pointed to static members.
  2. The address stored in pointers to members are offset to the class object address.
  3. Pointers to members must be used with class objects.
  4. Pointers to member functions cannot be used to show function address. Used to call function only.

References:
IBM publib

No comments:

Post a Comment