Archived

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

Assigning one function to another?

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

Hi, I''m starting an RPG battle system. When an action is chosen during combat, the appropriate move function is performed after "switch-caseing" the index of the action selected. Ex. switch(index) { case ATTACK: DoAttack(); break; case DEFEND: Defend(); break; } However, with this system I have to re-determin the selection every frame. I thought up a possible solution, but I''m not sure how to execute it. My character class has a function called Action(). Can I assign this function to another particular function? That is, make the character''s Action() function point to the appropriate function (such as Attack() or Defend()) and just call character.Action() each frame instead of re-determining the chosen move every frame?

Share this post


Link to post
Share on other sites
Are you doing this using OOP? If so, you can use something called virtual functions to do exactly what you are looking for. If you are just using straight C code, you can create a function pointer called Action, but you still will have to have a switch statement to update the function pointer (so that will not do what you are looking for).

Share this post


Link to post
Share on other sites
use a pointer to a function
such as
viod (*pfunc)();
that would point to a function that returns void and takes no paramiters just add paramiters inside the () at the end the way you would the funtion you want it to point to

change void to the return type you want

all possible funtions attack() defened() should accept same number of paramiters and return same type

Share this post


Link to post
Share on other sites

  
typedef void func(void);

void Attack1() { /*...*/ };
void Attack2() { /*...*/ };
void Attack3() { /*...*/
};

func* AttackTable[3] = { Attack1, Attack2, Attack3 };

...

func* MyAttack = AttackTable[2];

...

MyAttack();


Before you ask, this does not easily map to (non-static) class member functions, because pointers to (non-static) member functions are not pointers (they are ''pointer-to-member''s).

Go to function-pointer.org for more details.
Go to Boost for an object-oriented solution.

Documents [ GDNet | MSDN | STL | OpenGL | Formats | RTFM | Asking Smart Questions ]
C++ Stuff [ MinGW | Loki | SDL | Boost. | STLport | FLTK | ACCU Recommended Books ]

Share this post


Link to post
Share on other sites