Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

emileej

Pointing to a function

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

I did this a long time ago and most regretably forgot all about it. In my class I need a public variable which is a pointer to a function so that I can in public scope assign a new function to the pointer and later call that function throug that pointer. "On a long enough timeline the survival rate of everyone drops to zero" - Fight Club

Share this post


Link to post
Share on other sites
Advertisement
Everything you''ve ever wanted to know about function pointers:
http://www.function-pointer.org/

(well, almost everything)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
For regular functions or class static functions you can use the following, simply change the return types and argument types to what you need:

#include <cstdlib>
#include <iostream>

using namespace std;

// a convenient name to use instead of the
// more complicated syntax.
typedef void (*FUNCTION_POINTER)();

// used as an example
void original()
{
cout << "i''m the original function.\n";
}

// used as an example
void modified()
{
cout << "i''m the modified function.\n";
}

// fp is a global function pointer
// that initially points to original()
FUNCTION_POINTER fp = original;

// set fp to point to a new function and return the
// function it pointed to previously.
FUNCTION_POINTER set_function_pointer(FUNCTION_POINTER f)
{
FUNCTION_POINTER old = fp;
fp = f;
return old;
}

int main()
{
// call original() through the function pointer fp
fp();

// set fp to point to modified
FUNCTION_POINTER old = set_function_pointer(modified);

// call modified() through fp
fp();

// reset the original function
set_function_pointer(original);

// make sure it worked
fp();

system("PAUSE";
}

Share this post


Link to post
Share on other sites

  • 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!