I'm trying to wrap my head around pointers to member functions and am stuck with this example:
#include <iostream> class TestClass { public: void TestMethod(int, int) const; }; void TestClass::TestMethod(int x, int y) const { std::cout << x << " + " << y << " = " << x + y << std::endl; } int main() { void (TestClass::*func)(int, int) const; func = TestClass::TestMethod; TestClass tc; tc.func(10, 20); return 0; } What I think the code should do:
- In the first line of main I declare a pointer to a member function of
class TestClass, which returns nothing/takes twoint's and is declaredconst, called func. - The second line assigns the member-function
TestMethod(of classTestClass) tofunc, which satisfies these criteria. - The forth line creates an
TestClass-object called tc. - The fifth line tries to call the member function pointed to by
funcon theTestClass-objecttc.
I get two compilation errors:
Instead of assigning
TestClass::TestMethodtofunc. The compiler tries to callTestClass::TestMethod(even though it's notstatic, therefore throws an error):testPointerToMemberFunc.cpp:14:21: error: call to non-static member function without an object argument func = TestClass::TestMethod; ~~~~~~~~~~~^~~~~~~~~~The compiler tries to call a function named
funcontc, instead of the function, pointed to byfunc. To me this seems, likefuncisn't declared the right way (as a pointer to a member function):testPointerToMemberFunc.cpp:17:6: error: no member named 'func' in 'TestClass' tc.func(10, 20); ~~ ^
What am I doing wrong?