Pointers to Functions in a Class

Hi. I’m trying to do something a little complicated. I’m trying to create a pointer to a virtual function in an instance of a class I created, which isn’t of the baseclass type. Ideally, the function pointer should link to the derrived class’s function.

In code…

class CBaseClass
{
public:
virtual void Function( void );
};

class CDerrivedClass : public CBaseClass
{
public:
void Function( void ) { }
};

CBaseClass *object;

//Pretend we’re in a GLOBAL function, and everything has been initialized…

void (* Func)( void ) = object->Function;

/*This will generate the error (in MSVC++ 6.0)…

“Cannot convert parameter 1 from ‘void (void)’ to 'void (__cdecl *)(void)”

And I don’t know how to fix this. Any help would be greatly appreciated. Thanks a bunch! (Oh and typecasting doesn’t work…)*/

You want to store a method’s address in a regular function pointer variable?

All C++ methods (except static methods) have a hidden parameter called “this”. For example a method declared as
virtual void Function( void ); which appears to be parameterless is actually
virtual void Function( CBaseClass *this ) internally.

So your regular function pointer variable might be declared as
void (*Func)( CBaseClass *p );
Not sure if this would work but have a go.

By the way the “this” parameter is how a method is able to access fellow member variables from the same instance and method’s from the same class.

Declare your pointer to function this way:

void (* CBaseClass::Func)(void) = object->Function;

Compliler needs to know full information about the function pointer, including that it points to a class method. It’s related to the hidden “this” pointer that Frumpy
mentonied.