I have a problem with using a pointer to function in C++. Here is my example:
#include
using namespace std;
class bar
{
public:
void (
As the error says, methods belong to the class, not to individual instances. For this reason pointers to free functions and pointers to non-static methods are completely different things. You'll also need an instance to call the method on.
//declaring and taking the address of a foo's method
void (foo::*method)() = &foo::hello; //as the compiler nicely suggests
//calling a function through pointer
free_func();
//calling a method through pointer
foo instance;
(instance.*method)();
You can use libraries like Boost.Bind and Boost.Function (also in std::tr1 I think) to abstract away the difference and also bind an instance to the method:
#include
#include
#include
using namespace std;
class foo
{
public:
void hello(){cout << "hello" << endl;};
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
boost::function helloFunc(boost::bind(&foo::hello, testFoo));
boost::function byeFunc(byebye);
helloFunc();
byeFunc();
return 0;
}