Calling and initializing static member function of class

Viewed 45

I have the following code:

#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>

class A {
public:
 int f();
 int (A::*x)();
};

int A::f() {
 return 1;
}

int main() {
 A a;
 a.x = &A::f;
 printf("%d\n",(a.*(a.x))());
}

Where I can initialize the function pointer correctly. But I want to make the function pointer as static, I want to maintain single copy of this across all objects of this class. When I declare it as static

class A {
public:
 int f();
 static int (A::*x)();
};

I am unsure of the way/syntax to initialize it to function f. Any resource would be helpful

1 Answers

A static pointer-to-member-function (I guess you already know this is different from a pointer to a static member function) is a kind of static member data, so you have to provide a definition outside the class like you would do with other static member data.

class A
{
public:
   int f();
   static int (A::*x)();
};

// readable version
using ptr_to_A_memfn = int (A::*)(void);
ptr_to_A_memfn A::x = &A::f;

// single-line version
int (A::* A::x)(void) = &A::f;

int main()
{
   A a;
   printf("%d\n",(a.*(A::x))());
}
Related