C++: Pointer to class member function inside a non-related structure
-
13-09-2019 - |
Question
I've done a bit of reading online as to how to go about this and I think I'm doing it correctly... My goal is to have an array of structure objects that contain pointers to member-functions of a class.
Here's what I have so far...
typedef void (foo::*HandlerPtr)(...);
class foo
{
public:
void someFunc(...);
// ...
private:
// ...
};
struct STRUCT
{
HandlerPtr handler;
};
STRUCT stuff[]
{
{&foo::someFunc}
};
Then when calling the function using (stuff[0].*handler)(), with or without arguments (I do actually intend to use argument lists), I get "handler": Undeclared identifier...
I've got to be missing something, just don't know what.
Solution
someFunc() is not a static method, so you need a foo object instance in order to call someFunc() via your pointer-to-method variable, ie:
foo f;
f.*(stuff[0].handler)();
Or:
foo f;
HandlerPtr mthd = stuff[0].handler;
f.*mthd();
Or, using pointers:
foo *f = new foo;
f->*(stuff[0].handler)();
delete f;
Or:
foo *f = new foo;
HandlerPtr mthd = stuff[0].handler;
f->*mthd();
delete f;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow