Skip to content

Container of surrogates

January 12, 2007

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[100];
No. Vehicle is an abstract class. Slicing (truncation) on assignment of a derived class into an element of the array.

2. Vehicle* lot[100];
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,

VehicleSurrogate lot[100];
Auto x;
lot[1] = x; // calls VehicleSurrogate(x), deletes old associated object, copies new one

A problem remains, you’re storing copies of the target object.

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: