C++ newbie: how can I pass a function as an argument to another function?

Antst

New member
Joined
Jul 29, 2010
Messages
24
Reaction score
0
Points
1
Hello all:

1) Is it possible to pass a function (1) as an argument to another function (2)?
2) If so, how should it be done? Should the declaration/definition of function 2 contain all the function arguments and type of function 1?
3) Is it good style?

I remember seeing an example once where someone did this, but I have spent a lot of time on Google and can't find anything. I'm not sure if this is because I'm using incorrect search terms or if it just isn't a good idea to pass functions to other functions.

If anyone could tell me whether there are any pitfalls in doing this, I would very much appreciate it.

Thanks a lot for any help!
 
1) yes, you can use function pointers.

2) here is a short example how it is done in C:
#include <stdio.h>
void my_int_func(int x)
{
printf( "%d\n", x );
}


int main()
{
void (*foo)(int);
foo = &my_int_func;

/* call my_int_func (note that you do not need to write (*foo)(2) ) */
foo( 2 );
/* but if you want to, you may */
(*foo)( 2 );

return 0;
}

In C++ you can use virtual functions which are a little bit easier to handle (google them).

3) Working with pointers in general can be tricky at first, but is pretty straight-forward and powerful if you get used to it. And using function pointers / virtual functions is very, very common.
 
Back
Top