8 Years never needed a function pointer and I can't find a good example.
Function pointers are kind of a weird tool in your toolbox. People are normally taught function pointers in an academic/abstract setting and then they are quickly forgotten because you can get by without them on a day to day basis. So here is a real world example.
I recently used function pointers (C# delegates) in a generic Credit Card Processing library that I wrote for my employer. It needed to work across all the C# projects who had different data-layers. I had a very specific series of events I wanted to happen when sending a credit card transaction as it was being used to make it bullet proof.
- Save the credit card transaction attempt BEFORE sending to the processor - Status: About to Send
- Send the transaction to the processor
- Save the result of the credit card transaction - Status: Approved/Denied
I could have solved this problem with documentation. Hey jerkies! Do it like I told you! But, if they didn't use it correctly, the burden of figuring out the problem was going to be on my shoulders anyway. So I'd rather be sure.
I could have solved the problem with direct saves through one of the data layers. But then I'd have to copy/paste the code in each project and rewrite the saves for each data layer. If there was a bug, I'd have to fix it in each copy of the code... Bleh.
So, I decided to use function pointers (C# delegates). The signature was:
bool PersistTransaction(CreditCardTransactionInfo)
I didn't care how they saved it, I just tell them the info they need to save. If there is a problem saving the data, they should return false to me so I don't try to go through with the transaction. This allowed them to use the data layer they felt like using. Heck, they could have even saved it to a file instead of into the database if they felt like it.The more junior programmers started murmuring amongst themselves and claimed I was a dark sorcerer...
In games, you might use function pointers to control simple AI movements for sidescrolling shooters. Basic enemies might just move straight, others might follow a sin curve, and others track the player like a heat seeking missile. You can solve this problem without function pointers, but it opens up some neat possibilities.
- Eck