What's the point of Function Pointers?

Started by
14 comments, last by abstractworlds 19 years, 4 months ago
Function pointers aren't type safe? I'm pretty sure they give errors on compile if you pass the wrong type... As for functors, they are ok generally but are much bulkier (in code) than function pointers.

I personally chose to use function pointers for my GUI system, and for interpolators I support pointers to variables, pointers to functions, pointers to members, and functors.
Advertisement
All right, here we go. Why use function pointers when you can use delegates?

The article reveals ugly details about static and member-function pointers, and how you can do better.
Use virtual functions since that's what they are? organized member-function pointers?

In C++ you can use something like boost::function or Loki::Functor along with boost::bind to easily create concrete classes for designs using delegates.
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Just another example: I use function pointers to register functions to the virtual machine for my scripting language. Thats pretty useful if you ask me!
Function pointers ARE type safe (well, as safe as any pointer in that you can cast them however you want but w/o casting they're safe), and mainly they're made for function tables (when you need to call one of many functions based on an index).

In C++, virtual functions can solve most of the same problems as function pointers with the added benefit that they can take advantage of member data. There are still situations where you might need raw function pointers, but from what I've heard boost wraps those cases rather well so if you're using boost you pretty much don't need them except where APIs require them.
"Walk not the trodden path, for it has borne it's burden." -John, Flying Monk
Function pointers were introduced in the C language, and like many C language features, they were extremely useful when you only had the C language. But now that there are other (and sometimes better) C++ ways of doing things, function pointers aren't needed as much as they used to be.

For instance with plain C, you could give a C struct a more object-oriented feel by having function pointer members within a struct. This gave you a 'class-like' struct containing data and functions to operate on that data. Nowadays in C++ you would just use a class!

This topic is closed to new replies.

Advertisement