user3830775 user3830775 - 11 months ago 72
C++ Question

C++ pointer to member function not a function pointer

Let's say I have the following definitions:

class ScriptInterpreter {
class cell;
typedef ScriptInterpreter::cell (ScriptInterpreter::*proc_t) (const std::vector<cell> &);

class cell {
proc_t proc;

ScriptInterpreter::cell proc_add(const std::vector<cell> & c);

And the following code going on:

ScriptInterpreter::eval(ScriptInterpreter::cell cell, environment * env)
// ...

ScriptInterpreter::cell c;
c.proc = &ScriptInterpreter::proc_add;

return (c.*proc_)(exps);

At the line where I try to call the function pointer I get the error

error: called object type 'proc_t' (aka 'ScriptInterpreter::cell (ScriptInterpreter::*)(const std::vector<cell> &)') is not
a function or function pointer

When I add the * in front of the func so the line looks like this:

ScriptInterpreter::cell c = (proc_cell.*proc_)(exps);

it produces this:

error: use of undeclared identifier 'proc_'

I already looked at Callback functions in c++ and other problems of that kind, but nothing really gave me a hint what's wrong or provided any information about my error. I definitely don't have any names twice or something of that kind.
Also after reading what is an undeclared identifier error and how do i fix it I'm pretty sure I got everything alright.

So what am I doing wrong?

Edit: updated the code with real code instead of placeholder code

Answer Source

In order to call a member function through a pointer of pointer-to-member type, you have to use either operator .* or operator ->*. And on the left-hand side you have to specify the object for which you want to invoke that member function.

In your case an attempt to do that could look as follows

A::B b_object;
b_object.func = &A::func_to_call;

A a_object;
A::B other_b_object = (a_object.*b_object.func)();

Note that since the pointer is declared as pointing to a member of A, the .* operator need an object of type A on the left-hand side.

However, in your specific case this is ill-formed since b_object.func is private and no accessible from main.

P.S. int main, not void main.