Teen Programmers Unite  
 

 

Return to forum top

C++ Question

Posted by Kruptos [send private reply] at April 04, 2003, 04:21:39 PM

Hi, I've got a bit of a dilemma here that I'm not quite sure how to go about solving. What I need is a method of calling a function by name via another function. Here's an example to elucidate:


// The function definitions
void call_function(char *funct_to_call)
{
... call function funct_to_call()...
}

void do_stuff()
{
... some stuff ...
}

// And the call
call_function("do_stuff");


My question, as I've said, is how can I make it so that call_function() will call do_stuff() based on the argument it gets. Also, the actual function definitions need not look anything like this. Any help would be appreciated.

Posted by Psion [send private reply] at April 04, 2003, 06:30:10 PM

It's not possible to do in general. You can, however, create a structure that associates strings with function pointers, and then do look-ups in that structure. You must, of course, be sure to include all functions you want to call by name in this structure at the time when you compile it.

Posted by 142857 [send private reply] at April 04, 2003, 09:17:10 PM

Or, if you don't want the argument to be a string, you could have the function take an argument that is a pointer to a function:

void call_function(void (*func)())
{
(*func)();
}

Note that a function pointer's paramter(s) and return type have to be the same as the pointee function. So for the one above, the "void" is specifying the return type, and then the (*func) because of operator precedence, and then the other set of () for the parameters (could have been "(void)").

I think the syntax is right...correct me if I'm wrong.

Posted by Kruptos [send private reply] at April 04, 2003, 11:39:31 PM

Both of those methods should work fine for what I'm trying to accomplish. Thanks.

You must be logged in to post messages and see which you have already read.

Log on
Username:
Password:
Save for later automatic logon

Register as a new user
 
Copyright TPU 2002. See the Credits and About TPU for more information.