I’d like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I’m doing this are complicated.
In this example, I would like the output to be “1”
class A {
public:
int f();
int (*x)();
}
int A::f() {
return 1;
}
int main() {
A a;
a.x = a.f;
printf("%d\n",a.x())
}
But this fails at compiling. Why?
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class:
a.xdoes not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the objecta. Prependingaanother time as the left operand to the.*operator will tell the compiler on what object to call the function on.