Question

I have a pointer to a member function defined within a class, e.g.:

class Example {
   void (Example::*foo)();

   void foo2();
};

In my main code, I then set foo as:

Example *a;
a->foo = &Example::foo2;

However, when I try to call foo:

a->foo();

I get the following compile time error: "error: expression preceding parentheses of apparent call must have (pointer-to-) function type". I'm assuming I'm getting the syntax wrong somewhere, can someone point it out to me?

Was it helpful?

Solution

to call it you would do: (a->*(a->foo))()

(a->*X)(...) - dereferences a member function pointer - the parens around a->*X are important for precedence.

X = a->foo - in your example.

See ideone here for working example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top