Passing Methods in C++
From Exterior Memory
It is possible to storage a pointer to a method or function, and pass this as an argument to other methods and functions. This is useful for callback mechanisms.
Pointer-to-Function
To define `fptr` as a pointer-to-function:
bool (*fptr)(void);
To assign it:
fptr = &my_first_test;
To call `fptr`:
result = (*fptr)();
Example in a small application that runs two tests:
#include <iostream> #include <string> bool my_first_test() { return 1 + 1 == 2; } class ApplicationTest { public: void run_all_tests() { run_test(my_first_test, "my first test"); run_test(my_second_test, "my second test"); } bool run_test(bool (*test_method)(void), std::string test_name) { std::cout << "Running " << test_name << " ... "; bool test_result = (*test_method)(); std::cout << (test_result ? "success" : "failed") << std::endl; return test_result; } static bool my_second_test() { return 6 * 7 == 42; } }; int main(int argc, char *argv[]) { ApplicationTest *app = new ApplicationTest(); app->run_all_tests(); return 0; }
Pointer-to-Method
To define `mptr` as a pointer-to-method:
bool (ApplicationTest::*mptr)(void);
To assign it:
mptr = &ApplicationTest::my_first_test;
To call `mptr`:
result = (this->*mptr)();
Example in a small application that runs two tests:
#include <iostream> #include <string> class ApplicationTest { public: void run_all_tests() { run_test(&ApplicationTest::my_first_test, "my first test"); run_test(&ApplicationTest::my_second_test, "my second test"); } bool run_test(bool (ApplicationTest::*test_method)(void), std::string test_name) { std::cout << "Running " << test_name << " ... "; bool test_result = (this->*test_method)(); std::cout << (test_result ? "success" : "failed") << std::endl; return test_result; } bool my_first_test() { return 1 + 1 == 2; } bool my_second_test() { return 6 * 7 == 42; } }; int main(int argc, char *argv[]) { ApplicationTest *app = new ApplicationTest(); app->run_all_tests(); return 0; }
Further Reading
For much more technical detail, see C++ Tutorial: Pointer-to-Member Function.
[[Category::C++]]