Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a method's address in a class?

Tags:

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?

like image 288
Reck Hou Avatar asked Dec 21 '22 23:12

Reck Hou


2 Answers

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

like image 79
Nawaz Avatar answered Dec 24 '22 03:12

Nawaz


To store a pointer to a class function you need something special, a pointer to a member. Here you can find a good explanation

In short, a member function can't be stored in a normal function pointer as it need to be handed a this pointer to the current class. A static member function works like a normal function as it need no this pointer.

like image 36
Fionn Avatar answered Dec 24 '22 03:12

Fionn