Consider a scenario where there are two classes i.e. Base and Derived. If the Base class wants to call a function of the derived class, it can do so by either making a virtual function and defining that VF in the derived class or by using callbacks. I want to know in what should be preferred out of the two? Choosing among the two depends on which situations/conditions?
EDIT: Question Clarification:
The situation I was referring to is that there is a base class which receives messages. These different messages are to be handled differently by the derived class, so one way is to create a virtual function and let the derived class implement it, handling every message though various switch cases.
Another way is to implement the callbacks through the function pointers (pointing to the functions of derived class) inside the templates (templates are needed for handling the object of the derived class and the function names). The templates and the function pointers are going to reside in the base class.
A virtual function call is actually a callback.
The caller looks up the corresponding entry in the object's virtual function table and calls it. That's exactly like a callback behaves, except that member function pointers have awkward syntax. Virtual functions offload the work to the compiler, which makes them a very elegant solution.
Virtual functions are the way to communicate within the inheritance hierarchy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With