Today I am going to tell you about a potentially unforseen feature of the C++ language (or rather the compiler's interpretation of the language) that makes using callbacks not just difficult (you already knew that!), but deadly. Let me explain:
Assume you have a base class called cBase, with a derived class cDerived. The base class defines a linked list of cBase:: callbacks, and also a plethora of methods for manipulating the list.
Now cDerived defines a new function with a signature compatible with the list, and with a little static_cast<> prodding, pushes the function into it. At some later time, the list is traversed, and the functions are invoked. Crash! What the hell happened, you say?
The culprit was in derefrencing (both implicitly and explicitly) the "this" pointer(!) on cDerived's members within the functions. Even though the functions were declared within the class using them, because of the cast, they are rendered virtually useless! You simply cannot make it work! Wow, that sucks, you say. Oh, but that's not all!!
So being the clever shmuck that you are, you decide to give cBase a new member, a void * pointer named "work_around", and cDerived a pointer to a cDerived named "This". You pass "this" into the cBase function that swallows callbacks, and point "work_around" to it. Later, in cDerived's constructor, you cast "work_around" into a cDerived and assign it to "This". The functions themselves internally use "This->", not "this->"... sounds bulletproof, right?
Well, unless there is some flaw in my logic here(or even my compiler), no. The results were identical. The moral of the story is that C++ is not perfect, and can be quite a pain at times. Having said that, I cannot see myself parting with it any time soon, but -to be sure - whatever ugly hack I must come up with to work around this obnoxious problem will always serve as solemn reminder to me that SOMEDAY...I MUST WRITE MY OWN COMPILER!!!
You have been forewarned!