Static member function pointer to hold non static member function

Posted by user1425406 on Stack Overflow See other posts from Stack Overflow or by user1425406
Published on 2012-06-28T03:08:41Z Indexed on 2012/06/28 3:16 UTC
Read the original article Hit count: 199

Filed under:

This has defeated me. I want to have a static class variable which is a pointer to a (non-static) member function. I've tried all sorts of ways, but with no luck (including using typedefs, which just seemed to give me a different set of errors). In the code below I have the static class function pointer funcptr, and I can call it successfully from outside the class, but not from within the member function CallFuncptr - which is what I want to do. Any suggestions?

#include <stdio.h>

class A
{
public:
  static int (A::*funcptr)();
  int Four() { return 4;};
  int CallFuncptr() { return (this->*funcptr)(); } 
      // doesn't link -  undefined reference to `A::funcptr'
};
int (A::*funcptr)() = &A::Four;

int main()
{
  A fred;
  printf("four? %d\n", (fred.*funcptr)());  // This works
  printf("four? %d\n", fred.CallFuncptr()); // But this is the way I want to call it
}

© Stack Overflow or respective owner

Related posts about c++