Pointer To A Class Member

A pointer to a class member is not a real pointer, meaning that it does not contain the memory address of an object, but rather its offset within a class. Once a pointer to a class member has been assigned the offset of a member within a class, the actual value of the member can be retrieved within an object by using the .* operator. If an object is being accessed through a pointer, the ->* operator must be used. In the following example a class AClass is defined. Then a pointer to a class member is declared:
int AClass::*pToIntMember; 
and a pointer to a function member is declared:
void (AClass::*pToVoidReturningFunction)(int y);
pToIntMember can then be assigned the offset of any int member within AClass. On the other hand pToVoidReturningFunction can be assigned the offset of any function taking an int parameter and returning void within AClass. All in all, pointers to class members can be used to navigate through members of the same type within a certain class.

Example


#include <iostream>
#include <string>

using namespace std;

class AClass 
{
public:
    int a;

    void seta(int x) 
    {
        a = x;
    }
};

int main() 
{
    // Pointer to an int member
    int AClass::*pToIntMember;  

    // Pointer to a function member taking an int parameter and returning void
    void (AClass::*pToVoidReturningFunction)(int y); 

    // Assign the offset of a to the pointer
    pToIntMember = &AClass::a; 

    // Assign the offset of seta to the function member pointer
    pToVoidReturningFunction = &AClass::seta; 
    
    // Create two objects
    AClass obj1;  
    AClass obj2;

    // Call seta() through the member pointer
    (obj1.*pToVoidReturningFunction)(10); 
    (obj2.*pToVoidReturningFunction)(1000);

    // Print a through the int member pointer using the .* operator
    cout << obj1.*pToIntMember << endl; 
    cout << obj2.*pToIntMember << endl;

    // Declare a pointer to an object and assign obj1's addr. to it 
    AClass *pAClass = &obj1;           

    // Print a's value for obj1 through ->*
    cout << pAClass->*pToIntMember << endl;   
    
    // Print a's value for obj2
    pAClass = &obj2;
    cout << pAClass->*pToIntMember << endl; 
}

Output

10
1000
10
1000