I am trying to understand function pointers and I have the following test code:
#include <iostream>
using namespace std;
class Test {
public:
void test_func() {
cout << "Test func called.";
}
};
void outer_test_func(Test &t, void (Test::*func)()) {
(t.*func)();
}
int main(int argc, char *argv[]) {
auto t = Test();
outer_test_func(t, &Test::test_func);
}
This works. But from what I understand Test::test_func
and &Test::test_func
both result in pointers. So why can't I use the former instead of the latter? If I try it g++ complains.
But from what I understand Test::test_func and &Test::test_func both result in pointers.
Test::test_func
is not a valid syntax for creating pointer to member function, nor pointer to data members. It has never been a valid C++ syntax.
From cppreference (emphasis mine),
A pointer to non-static member object m which is a member of class C can be initialized with the expression &C::m exactly. Expressions such as &(C::m) or &m inside C's member function do not form pointers to members.