Jump to content
  • Advertisement
Sign in to follow this  
Endar

pointer to function - pointer to member function

This topic is 4709 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

Just for fun, I'm trying to convert a pointer to a member function to a pointer to a non-member function.
class A
{
public:
	int s;

	A():s(5)
	{	}

	void func()
	{
		std::cout << s << std::endl;
	}
};

int main()
{
	void (*f)(A*);

	A a;

	f = (void (__cdecl*)(A*)) A::func;

return 0;
}

I got to this point, and, it doesn't work:
error C2440: 'type cast' : cannot convert from '' to 'void (__cdecl *)(class A *)'
And I'm not sure what to try now.

Share this post


Link to post
Share on other sites
Advertisement
Don't bother. Pointers to member functions have a very different structure than normal pointers to functions. Pointer to member functions can be up to four times the size of a pointer to a normal function, so trying to stuff it in will lose data.

Share this post


Link to post
Share on other sites
As I understand it, taking the address of a class method may or may not actually point to the address of the function. It could, instead, point to...something else, I assume =).

Read the C++ FAQ Lite, it explains much better than I. Click here for the best warning label.

EDIT: Also, I noticed that in your original example you're trying to use the __cdecl calling convention -- if this was in C, that would be closer to the "correct" solution, though, as above, it may or may not point to what you actually want. In C, methods and function pointers are different because of calling convention; in C++, they're different because of the way they're represented (having a really hard time expressing this, considering I don't fully understand it).

Share this post


Link to post
Share on other sites
Thanks, but I wasn't really trying to do anything. It's just one of those things where you sit up and say "I wonder if that is possible?".

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!