0

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)?

2
  • Only put in the H file what is required outside the cpp file. Should any other entity ever have access to that information? if yes, .h if no, .cpp. With such a simple project it doesn't really matter. Commented Oct 17, 2012 at 23:03
  • Really a matter of taste. I would initialize the array in the header file. Commented Oct 17, 2012 at 23:03

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

+1 just curious, can you have a pointer to a function pointer? and if so your array could store those, no?
@AK4749: As with integers, a pointer to an integer pointer is another indirection to the same data type. Each function signature is treated as a distinct type for function pointers. So, a pointer to a function pointer won't help people who need a pointer to any function.

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.