Jump to content
  • Advertisement
Sign in to follow this  
DudeMiester

Function Pointer Problem

This topic is 4994 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!