0

Let's say I have the following definitions:

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

class cell {
public:
  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

Community
  • 1
  • 1
  • 1
    Firstly, there's no `B` in your code. Only `A::B`. It is better to post real code for your `main`, so that people understand what you are talking about. – AnT stands with Russia Oct 31 '16 at 00:56
  • You need an object of `A` (not `B`) to call it, since it's a pointer to `A`'s member function. – songyuanyao Oct 31 '16 at 00:58
  • B doesn't belong to A – Raindrop7 Oct 31 '16 at 00:59
  • **`void main`** has never been valid in either C or C++. Who taught you to write that? It's one character more to write just in order to get non-portable code that most readers cannot just copy and paste to try. Worse, it misleads other novice programmers, so please don't post code with `void main`. FTFY. – Cheers and hth. - Alf Oct 31 '16 at 01:05

1 Answers1

0

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.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765