Sign in to follow this  
DudeMiester

Function Pointer Problem

Recommended Posts

class A
{
	void (*varFunc)();
public:
	inline void Func()
	{
		varFunc();
	}
	A(void (*myFunc)()) : varFunc(myFunc)
	{
	}
};

class B : public A
{
	void myFunc()
	{
		cout<<"Func"<<endl;
	}
public:
	B() : A(&myFunc)
	{
	}
};

int main()
{
	B Test;
	Test.Func();
}

This is what I'm trying to do. It won't work and the compiler gives me this error: error C2276: '&' : illegal operation on bound member function expression So I tried useing &B::myFunc and the compiler gave me this error: error C2664: 'A::A(void (__cdecl *)(void))' : cannot convert parameter 1 from 'void (__thiscall B::* )(void)' to 'void (__cdecl *)(void)' So is it possible to do what I'm trying to do?

Share this post


Link to post
Share on other sites
The signature for a class method does not match that for a non-class function. The difference is one of calling convention - __thiscall vs __stdcall - which means that they pass their parameters differently. A workaround is to make the class method static, but that can introduce certain constraints.

A more robust solution is to use a functor or function object:


struct Functor
{
Functor()
{
// any initialization
}

void operator () ()
{
// do whatever
}
};

...

Functor f;
..
f(); // invokes functor just like a function pointer


If you make the Functor class an interface, or at least a base class, then all classes derived from it can be invoked through polymorphic dispatch.

For reference, though: www.function-pointer.org.

Share this post


Link to post
Share on other sites
Hmm...I'm not really sure what you're trying to do with varFunc(myFunc) in the constructor for class A.

Are you...trying to set it to the value of myFunc? I didn't think that you could do that with function pointers. But then again, I just recently learned how to use them, so many of the uses are, uh...Greek to me.

Still, I'll try to help as much as I can here.

Share this post


Link to post
Share on other sites
lol, I actually used functors without knowing it for my problem. See I had this problem a while ago, but I never bothered to ask about it until now. So yeah, the code I wrote as it turns out is basically just used a functor and that works fine.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this