Skip to end of metadata
Go to start of metadata

To store a function in a variable in C++, you just need to store the address of a function in the pointer variable. I declare the variable in my code as "void (*foo)(int)" where the first part is the return type, the second is the name of the variable, which is a pointer, and the third is the return type of the function. As long as the return and argument type match, the variable can be used to represent any function. To define the variable, I use "foo = &storedFunc1".

Next, to pass in a function as a parameter to another function, I just have to declare the inner function (the one that is passed in) in a different way. I use "typedef void (* innerFunc)(int arg1, int arg2)" in my code to define a function type called "innerFunc" that returns void and takes in two int arguments. Then, when I call the upper function, I pass in two ints and "(innerFunc)calledFunc", because the upper function takes in a function of type "innerFunc". So C++ lets you make a custom type for functions that can be passed in.


Pictured above: typedef is used to define a function that can be passed in. Also, topFunc (function that takes others in) and calledFunc (the function of type innerFunc) are defined.

typedef is a keyword that can be used to declare but not define a function in C++.

Labels
  • No labels