Creating Dynamically Typed ObjectsSource: comp.lang.c++.moderatedDate: 23-Nov-97
Problem: How can you create objects if their exact sub-type is unknown at compile time?
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.
James Kanze answered: Basically, you'll need to do the following things:
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). 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
|