C++ – How to get a method’s address in a class

c

Here is part of my code:

In a.h:

class classA
{
public:
void (*function_a)(void);
classA();
void function_a();
};

In a.cpp:

void classA::classA()
{
  (*function_a)() = function_a;
}

void classA::function_a()
{
  return;
}

I want to get function_a's address and save it into void (*function_a)(void), but I got compile error that "expression is not assignable". What shall I do to solve this problem?

Best Answer

First of all, choose different names for different things.

Second, the non-static member function pointer should be declared as:

void (classA::*memfun)(void); //note the syntax

then the assignment should be as:

memfun = &classA::function_a; //note &, and note the syntax on both sides.

and you call this as:

classA instance;
(instance.*memfun)();

That is what you do in C++03.

However, in C++11, you can use std::function as well. Here is how you do it:

std::function<void(classA*)> memfun(&classA::function_a);

and you call this as:

classA instance;
memfun(&instance); 

Online demo