Solved. Related question: Is there a way to create a function pointer that can point to a member of any class?
Can someone share with me the correct way to use a function belonging to another class through function pointers? Neither of these seem to work:
Code:
#include <iostream>
#include <string>
using namespace std;
class newtest
{
int newtest::addMe(int a, int b)
{
return a + b;
}
newtest::newtest(int (*functocall)(int,int))
{
int result = (*functocall)(1,2);
cout << result;
}
int main ()
{
cout << "First attempt: 1 + 2 = ";
newtest thisTest(newtest::addMe); // Error here
cout << endl << "Second attempt: 3 + 4 = ";
int (*reffunc)(int,int) = newtest::addMe; // Error here
int result = (*reffunc)(3,4);
cout << result;
string dontcare;
cin >> dontcare;
return 0;
}
};
I've tried with and without the newtest:: preceeding the function name. This will not compile in VC++ 2010. The compile error is not very helpful. "error C3867: 'newtest::addMe': function call missing argument list; use '&newtest::addMe' to create a pointer to member" for both lines. When I add the &, it just changes the error message to an illegal operator one.
The mouseover messages are a little more descriptive. The first line gives "no instance of constructor 'newtest::newtest' matches the argument list". The second line "a value of type 'int (newtest::*)(int a, int b)' cannot be used to initialize an entity of type 'int (*)(int,int)'".
What do you guys think?