Calling function pointer functions
I am having trouble calling a function pointer inside a struct. I used this approach before classes, but now when I try to use it inside a class method using pointers to other class methods ... I get a compiler error. Here is my class:
class Myclass
{
int i;
void cmd1(int)
{}
void cmd2(int)
{}
void trans()
{
const struct
{
std::string cmd;
void (Myclass::*func)(int)
}
CmdTable[] =
{
{ "command1", &Myclass::cmd1 },
{ "command2", &Myclass::cmd2 }
};
CmdTable[0].func(i);
CmdTable[1].func(i);
}
};
Lines CmdTable[0].func(i);
and CmdTable[1].func(i);
both provide the following error: Error: Expression must be of function type (pointer-to-function).
I understand that there are probably better ways to do this, but I am very curious as to why what I have written is not working. Any explanation would be greatly appreciated.
source to share
The member pointer function is a pure class. You need to combine it with an instance of the class to make a complete function call. For example, to use an instance *this
, you can use an operator ->*
and say:
(this->*CmdTable[0])(i);
Or, you can use an operator .*
for the value of an object:
(*this.*CmdTable[0])(i);
The last form is always correct. For the first, note that it operator->*
can be overloaded and do something unrelated.
source to share