C++ using function as parameter

Normally, for readability’s sake, you use a typedef to define the custom type like so:

typedef void (* vFunctionCall)(int args);

when defining this typedef you want the returning argument type for the function prototypes you’ll be pointing to, to lead the typedef identifier (in this case the void type) and the prototype arguments to follow it (in this case “int args”).

When using this typedef as an argument for another function, you would define your function like so (this typedef can be used almost exactly like any other object type):

void funct(int a, vFunctionCall funct2) { ... }

and then used like a normal function, like so:

funct2(a);

So an entire code example would look like this:

typedef void (* vFunctionCall)(int args);

void funct(int a, vFunctionCall funct2)
{
   funct2(a);
}

void otherFunct(int a)
{
   printf("%i", a);
}

int main()
{
   funct(2, (vFunctionCall)otherFunct);
   return 0;
}

and would print out:

2

Leave a Comment