C ++ member pointer function call

I have a pointer to a member function defined inside a class, for example:

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

In my main code, I 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: the expression preceding the parentheses of the visible call must have (function type" pointer-to-function ""). I guess somewhere I get the syntax, can someone point me to this?

+6
source share
1 answer

to call it: (a->*(a->foo))()

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

X = a->foo - in your example.

See ideone here for a working example.

+13
source

Source: https://habr.com/ru/post/969352/


All Articles