VesmirPendel
VesmirPendel

Reputation: 33

An Array of Function Pointers in C++

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!

Upvotes: 3

Views: 151

Answers (1)

Shoe
Shoe

Reputation: 76240

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.

Upvotes: 5

Related Questions