5

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?

Shane Hou
  • 4,808
  • 9
  • 35
  • 50

4 Answers4

10

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • caution: gcc 4.9.2 on https://www.codechef.com/ide gave compilation error on 3/17/2017 with the code at http://ideone.com/kQuZQ. cpp.sh compiled it. Moral: try different before concluding anything. – qqqqq Mar 17 '17 at 20:13
3

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.

Fionn
  • 10,975
  • 11
  • 54
  • 84
1

maybe you can rearchitect better whatever you are trying to do once you learn about some of these libraries:

1) if you use c++11, you can use std::function

2) otherwise if you are stuck with an old compiler, you can use boost::function

any of the these will provide the ability to pass a function for later invocation.

lurscher
  • 25,930
  • 29
  • 122
  • 185
-2

Nawaz has already explained how to do it correctly. There are a lot of restrictions on pointers to class member functions compared to pointers to global functions. The only exception are static member functions which are nearly the same es global functions, except that they are members of class's name space.

A C++ alternative to function pointers are function objects. These are classes which have one or several overloadings of operator():

class MyFunction
{
public:
    <return-type> operator() (... parameters ...);
};

Then you can do the following:

MyFunction fnct;
fnct(... args ...);

I.e., you can use the class instance like a function.

bjhend
  • 1,538
  • 11
  • 25