Search code examples
c++pointersmember

How to use and access static pointer-to-member value s_ptm inside class?


We can declare and use instance-level pointer-to-member value/func inside class. And using obj.*(obj.ptm) or ptr->*(ptr->ptm) pattern to access.

But if declare them as static type-level s_ptm value/func, how to initialize and access/use them?

class C
{
  public:
     static int s_i;
     static int C::* s_ptm; //declare static ptm value OK here
};

Q: How to initialize and access s_ptm?

coliru.stacked-crooked.com/a/44fa362afb8462ef


Solution

  • Pointers to static members are just plain pointers. You cannot assign a pointer to a static member to a pointer to member. The good news is: You don't need it. Pointers to members enable you to point to a member and then given an instance you can access its member via that pointer. For a static member this isnt needed, because all instances share the same static member.

    To initialize s_ptm you need an int member first:

    struct C {
        static int s_i;
        static int C::* s_ptm; //declare static ptm value OK here
        int c;
    };
    
    int C::* C::s_ptm = &C::c;     // OK
    //int C::* C::s_ptm = &C::s_i; // NOPE !
    int* p = &C::s_i;              // OK
    

    However, with only a single int member a pointer to member of type int is no that useful. Instead of accessing C::c via the pointer you can access it by its name. Pointers to members are useful when there is more than one member of the same type or in a generic context.