Skip to main content
GameDev.net gamedev.net
🔒 Locked

Function Pointers

Started by SloppyJoe Dec 6, 2001 at 3:11 PM 3 replies 450+ views
Original Post
SloppyJoe
SloppyJoe
After spending sometime trying to figure out pointers to functions I finally found out how they work. They are relatively simple. Suppose you had a function called DoSomething:
  
BOOL DoSomething(int nParameter)
{
     MessageBox(NULL, "This is a MessageBox", "Title", MB_OK);
     return(TRUE);
}
  
You would then make a pointer to a function like this:
  
//return_type (*var_name)(param_type)

BOOL (*lpfnDoSomething)(int);
(*lpfnDoSomething) = DoSomething;
  
And to call it:
  
(*lpfnDoSomething)(10);
  
That''s all. SloppyJoe
NewDeal
NewDeal
Thanks for sharing
EvilCrap
EvilCrap
yes, and casting looks like this:

long lfunc = (long)FUNCTIONADDRESS;
void (*pfunc)(int, int);
pfunc = (void(*)(int,int))lfunc;
invective
invective
Its a little easier to read if you typedef them so you don''t have to explicitly dereference the pointer everytime you make a call.

  
void print (void)
{
std::cout << "hi\n";
}

void main( void )
{
typedef void (*void_function_ptr) (void);
void_function_ptr myPrint = print;
myPrint ();
}


and don''t for get about the peculiarities of non static member functions (because of the implicit this parameter):
http://www.parashift.com/c++-faq-lite/pointers-to-members.html
LilBudyWizer
LilBudyWizer
Create a base class with your method declared as virtual. Create two or more classes derived off that base class that override or implement that method. Instantiate whichever is appropriate for the use needed, but store its pointer as a pointer to the base class. Then just call the method. That will call the function in the derived class for whichever class was actually instantiated. Polymorphism is your friend, learn it, use it.
Keys to success: Ability, ambition and opportunity.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.