Creating Dynamically Typed Objects

Source: comp.lang.c++.moderated
Date: 23-Nov-97

Related Sites


------------------------------

o-< Problem: How can you create objects if their exact sub-type is unknown at compile time?


---------------

o-< Jonathan Male asked:

I've got an arcade game developed in C++ using OOP. I need to implement a saved game feature, but [this] is proving to be difficult, due in part to C++'s [static] typing.

Example:

class TTo_Be_Saved {
  public:
    TBase_Class *Saved_Member;
};
When this object is loaded from disk, it will need to be constructed. The problem comes from not knowing the type of Saved_Member, as it may be a derived class. Thus, I can't construct it and call its Load() function.


---------------

o-< James Kanze answered:

Basically, you'll need to do the following things:

  1. Implement some sort of standardized (within your application) type naming, and write out the type of the object immediately ahead of the object itself.

  2. Define a builder class hierarchy in parallel to the TBase_Class hierarchy. Typically, the builder classes will be nested (member) classes of each class, although this is not necessary. Declare one instance of each builder class (typically, a static member of the class it builds). The builder class has a single virtual function, which constructs an object of the correct type, and returns the pointer to the base.

  3. Create a map between the type names and the instances of the builder class. I generally do this by having the constructor of the builder class register itself with the map -- attention to the order of initialization if you do this, however.

  4. When reading, read the type name, and use the map to get a pointer to the corresponding builder class.
This is basically the factory method pattern, with the map a singleton.

I generally use strings to name the types; if the set of types is closed, however, you can also use enum values (in which case, you can use a built-in array type as the map).


------------------------------

o-< More Info:

Dirk Baumer and Dirk Riehle, Product Trader (aka Late Creation)

Vince Huston, A short description of the Factory Method pattern

Marshall Cline, The Named Constructor Idiom (from the C++ FAQ)

James O. Coplien, Virtual Constructor


------------------------------