Container of surrogates
I’m still reading through, “Ruminations on C++“, and am thrilled to see all the issues that I fought through being illuminated and explained so clearly (such as memory management and OOD).
One problem the book describes is that of inheritance and containers.
Probem: You have a class hierarchy and you want to create a collection containing various objects from that hierarcy.
The book presents several solutions and the first one was Surrogate classes: “… [a class] which act mostly like objects that they want to represent, but allow a whole hierarchy to be collapsed into one.” Here is how the book developed the solution (in the book the collection is a simple array).
1. Vehicle lot;
No. Vehicle is an abstract class. Slicing (truncation) on assignment of a derived class into an element of the array.
2. Vehicle* lot;
No. Danger from dangling pointers if assigned to local object. Instead point to a copy of the object, but need to know static type of objects being assigned to array elements.
3. Add a virtual copy() function in the base class so that the (unknown) derived classes can return a proper copy to put into the array. The “virtual”, makes the call dynamic. Need to have a virtual destructor. Now need to worry about memory management.
4. Store surrogate that “stand-in” for the associated objects in the collection. Associated object persists as long as surrogate refers to it, so copying and assignment of surrogates affect associated objects lifetime. Need to provide same interface as that of the base class.
Purpose: Now you can do this,
lot = x; // calls VehicleSurrogate(x), deletes old associated object, copies new one
A problem remains, you’re storing copies of the target object.