3

I'm trying to figure out on how can I make an array of pointers to functions that are inside a class. Where an element in an array represents a unique function.

Tiles.h code:

class tiles: public box
{
    public:
        void north2east(float trans_x, float trans_y);
        void north2west(float trans_x, float trans_y);
        void south2east(float trans_x, float trans_y);
        void south2west(float trans_x, float trans_y);
};

Tiles.cpp code:

void tiles::north2east(float trans_x, float trans_y); { }
void tiles::north2west(float trans_x, float trans_y); { }
void tiles::south2east(float trans_x, float trans_y); { }
void tiles::south2west(float trans_x, float trans_y); { }

I've heard that you can do it by adding the following in the Tiles.cpp file:

typedef void (*FUNC_ARRAY) (float trans_x, float trans_y);
FUNC_ARRAY functions[] = {
    tiles::north2east,
    tiles::north2west,
    tiles::south2east,
    tiles::south2west
}

But this gives me the following error:

a value of type "void (tiles::*)(float trans_x, float trans_y)" cannot be used to initialize an entity of type "FUNC_ARRAY"

Tips and suggestions on solving the code are welcome!

3
  • 2
    That typedef can only be used for ordinary functions or static member functions. Commented Apr 9, 2015 at 9:17
  • See warplife.com/tips/code/c++/member-pointers.html for how to declare pointers to member functions. Commented Apr 9, 2015 at 9:17
  • You assign pointer to methods and those aren't pointers to functions as you cannot invoke them without an object instance. Commented Apr 9, 2015 at 9:18

1 Answer 1

5

Just change your typedef to:

typedef void (tiles::*FUNC_ARRAY) (float trans_x, float trans_y);
//            ^^^^^^^

Your current typedef can only be used for regular functions and static member functions. What you need there is a pointer to a member function.

Sign up to request clarification or add additional context in comments.

1 Comment

@VesmirPendel have in mind that now you will be able to invoke those method only on objects, like: tiles t; (t.*function[1])(1.0, 1.0); or tiles *t = new t; (t->*function[1])(1.0, 1.0);

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.