4

I am having trouble calling a function pointer inside a structure. I have used this approach before outside of classes, but now that I am trying it inside a class method using function pointers to other class methods.... I am receiving 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);
    }
};

The lines CmdTable[0].func(i); and CmdTable[1].func(i); both provide the following error: Error: expression must have (pointer-to-) function type.

I realize there are probably better ways of doing this, but I'm rather curious as to why what I've written doesn't work. Any explanation would be greatly appreciated.

Canoti
  • 43
  • 5
  • 2
    You might want to read about [`std::function`](http://en.cppreference.com/w/cpp/utility/functional/function/function) and [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/function/bind). – Some programmer dude Aug 22 '14 at 18:20
  • 1
    @JoachimPileborg: Why? Those are very heavy-weight, expensive "solutions" for a problem that doesn't need them. – Kerrek SB Aug 22 '14 at 18:27

1 Answers1

5

The pointer-to-member-function is a pure class property. You need to combine it with a class instance in order to make a meaningful function call. For example, to use the instance *this, you can use the operator ->* and say:

(this->*CmdTable[0])(i);

Or you can use operator .* on an object value:

(*this.*CmdTable[0])(i);

The latter form is always correct. For the former, note that operator->* may be overloaded and do something unrelated.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084