Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual functions versus Callbacks

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.

like image 382
Aquarius_Girl Avatar asked Apr 06 '11 10:04

Aquarius_Girl


1 Answers

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.

like image 174
Alexander Gessler Avatar answered Sep 24 '22 09:09

Alexander Gessler