Re: ? Function Pointer to a Method of Unknown Class
"Alec S." <@> wrote in message
news:OCNho$e2GHA.4116@TK2MSFTNGP02.phx.gbl
"Alex Blekhman" <xfkt@oohay.moc> wrote in message
news:uiMWLhY2GHA.4748@TK2MSFTNGP04.phx.gbl...
"Alec S." wrote:
I've got a class which needs to store a pointer to a
function. The class will use that as a callback to pass
some data to the
specified function when the data changes.
I need to be able to pass a method of the required format
from an unknown class to it.
You cannot cast pointer to member to pointer to regular
function. The simplest solution is to make it regular
callback and pass pointer to class' instance as a parameter.
Unfortunately that's what the research I did yesterday seems to say.
I did do as you suggested with another callback I wrote a while back
and will probably do that again since it's probably the easiest way
like you said. Thanks for the confirmation.
I just don't see why it shouldn't work. It seems like a perfectly
reasonable (and useful) thing to do, so I'm a little confused why
they would not have allowed it.
Because member functions and non-member functions are different, which means
that pointers to them are different. In particular, a member function must
be called from an object of the appropriate class so that it can access the
data members of that object. Further, if you point to a virtual member
function, then resolving the call may involve looking up a vtable to see
what concrete function is required, e.g.,
#include <iostream>
using namespace std;
struct Base
{
virtual void foo()
{
cout << "Base foo\n";
}
};
struct Derived : Base
{
void foo()
{
cout << "Derived foo\n";
}
};
typedef void (Base::*Fnptr)() ;
int main()
{
Fnptr fnptr = &Base::foo;
Base b;
Derived d;
(b.*fnptr)();
(d.*fnptr)();
return 0;
}
--
John Carson