C++ Function Pointers
-
What is function pointer
Function pointer is just a pointer to a function. You can then call function from a pointer or you can pass it to another function to call it from there.
-
How to write function pointer
You can get function pointer using
autokeyword and funciton name without()#include <string> void log(std::string str){ std::cout << str << std::endl; } auto function = log;or you can use function pointer type that looks like this:
// return_type (*Function_Ptr_Name) (parameter type, ...)here is in code
#include <string> void log(std::string str){ std::cout << str << std::endl; } void (*function) (std::string) = log;To use call function from pointer we just use pointer name and
()#include <string> void log(std::string str){ std::cout << str << std::endl; } void (*function) (std::string) = log; function();You can also pass function pointer to another function
#include <string> void log(std::string str){ std::cout << str << std::endl; } void anotherFunc(void (*func) (std::string)){ std::cout << "Hello world" << std::endl; func("world"); } void (*function) (std::string) = log; anotherFunc(function);