Callbacks in C++
You want to pass a class around by value, but at the same time the class
needs polymorphic behavior.
- The base class contains all of the data. Derived classes do not add
- The number of ploymorphic methods is small (preferably one).
- Passing pointers or references to objects requires policies for determining
who should clean up the object.
- You want to maximize efficiency by avoiding heap allocation and deallocation.
- You need polymorphic behavior in a class. To get polymorphic behavior
using "virtual" in C++, you must pass a pointer or a reference
to the object instead of passing by value.
The solution given is for the single polymorphic member function case.
- Remove the virtual keyword from the method in the base class.
- Add a function pointer to the base class that will call a function
that is passed the arguments that the formerly virtual method was passed
as well as one or more additional arguments that contain the base class
or data members of the base class. That function pointer must also point
to a function that returns the same type of data that the formerly virtual
- Rewrite the formerly virtual method so that it calls the function pointer
passing it the appropriate arguments and returning the function pointer's
return value as its own.
- Implement the derived classes so that they have a static method. Initialize
their base class passing a pointer to the static member function to the
base class. The static method will fill the role of overriding the formerly
polymorphic base class method.
- The solution allows passing the base class by value while still having
- Efficiency is maximized by avoiding the need for any heap allocation.
The other space and time overheads are less than or equal to the overhead
of standard polymorphic dispatch in C++.
While the Handle/Body pattern and Counted Body pattern [Coplien94] [Coplien92]
can be used, those solutions still require heap allocation to occur, those
techniques simply reduce how often heap allocation must be performed. For
classes that are sufficiently simple, it is better to avoid heap allocation
This technique is best for when creating a family of classes that are
an abstract data type and should have behavior and functionality similar
to a built in type.
Callbacks in C++
Copyright © 1996-2000 Paul Jakubik
Created: 26 July 1996. Last update: 26 November 2000.