2

I try to create an array of pointers of member function of my current class but without success for the moment...

I already tried many things, here is my code:

// Human.hpp

#include <iostream>

class Human
{
    private:
        void meleeAttack(std::string const & target);
        void rangedAttack(std::string const & target);
        void intimidatingShout(std::string const & target);
    public:
        void action(std::string const & action_name, std::string const & target);
};
// Human.cpp

#include "Human.hpp"

// ...

void    Human::action(std::string const & action_name, std::string const & target)
{
    std::string actionsStr[] = {"meleeAttack", "rangedAttack", "intimidatingShout"};

    typedef void (Human::*Actions)(std::string const & target);
    Actions actions[3] = {&Human::meleeAttack, &Human::rangedAttack, &Human::intimidatingShout};

    for (int i = 2; i >= 0; i--)
        if (actionsStr[i] == action_name)
        {
            actions[i](target); // there is an error HERE
            break;
        }
}

This code generate an error on compilation:

main.cpp:41:23: error: called object type 'Actions' (aka 'void (Human::*)(const std::string &)') is not a function or function pointer
            actions[i](target);
            ~~~~~~~~~~^
1 error generated.

What is the good way to do it ?

3
  • 1
    A pointer to a non-member function and a pointer to a member function is not the same. Pointers to member functions needs an object to be called on (what becomes the this pointer). You might want to read about std::function and std::bind. Commented Apr 4, 2017 at 11:29
  • 1
    You probably want to read about std::unordered_map as well. Commented Apr 4, 2017 at 11:31
  • Possible duplicate of C++ Call Pointer To Member Function Commented Apr 4, 2017 at 11:48

1 Answer 1

7
for (int i = 2; i >= 0; i--)
    if (actionsStr[i] == action_name)
    {
        (this->*(actions[i]))(target);
        break;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Why this works?
Because language rules

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.