Pointer to member function
-
Hi guys =) need a little help here... Shouldn't this work?
class MyClass
{
public:
void method() {}
void (MyClass::*_callback)();
};int main()
{
MyClass b;b._callback = &MyClass::method;
(b.*_callback)(); // error C2065: '_callback' : undeclared identifier
return 0;
}Fratelli
-
Hi guys =) need a little help here... Shouldn't this work?
class MyClass
{
public:
void method() {}
void (MyClass::*_callback)();
};int main()
{
MyClass b;b._callback = &MyClass::method;
(b.*_callback)(); // error C2065: '_callback' : undeclared identifier
return 0;
}Fratelli
No, it shouldn’t work. Replace this:
(b.*_callback)();
with this:
(b.*(b._callback))();
C++ member function pointers are not like delegates in C#. The pointer
MyClass::_callback
identifies a member function ofMyClass
which returnsvoid
and takes no parameters (and has the calling convention__thiscall
): it doesn’t specify which instance ofMyClass
. The fact that the pointer is a member of theclass
is incidental and is probably what’s confusing you.Steve