sgchako
sgchako

Reputation: 109

Declaring an array of function pointers in C++

I am working on a project with a .h file and a .cpp file. I'm writing a function that I want to take advantage of an array of function pointers, where each function in the array is called based on a condition related to an enum. I have declared the 5 functions and the array itself in my .h file. In which file should I set each value of the array equal to the appropriate function (.h or .cpp)?

Upvotes: 0

Views: 549

Answers (2)

Thomas Matthews
Thomas Matthews

Reputation: 57708

In general, variable assignments take place in the ".cpp" file. If you need it global, you would put something in a .h file.

Also, be aware that only one function pointer type can exist in an array. In other words, all the functions must have the same signature.

If you change the array to hold a function object, or a pointer to a function object, you could have many varieties of function objects that derive from a base function object.

See also std::vector and std::map.

Upvotes: 1

I predict you'd have issues if the array definition itself is in the .h file.

You should define the array (along with the setting of values) in your .c file.

And in the .h file declare the array as an extern, like so:

extern func_pointer_t array[];

But globals are a bad idea in general, you should consider supplying an API for getting a function pointer out of the array.

func_pointer_t get(unsigned int i);

Upvotes: 2

Related Questions