I go even further by making the map a static field of the base class and using a function call in the class header of each subclass: #ifndef TRAIN #define TRAIN class Train : public Base { ... }; namespace { void *dummyTrain = Base::addEntry( "Train", Train::create() ); } #endif where Base::addEntry() looks something like private: typedef Base *(*Create)( string& name ); public: void *addEntry( string Name, Create create ){ funcs[ name ] = create; return 0; } This allows the subclasses to add their own entries to the map, which is contained in the base class. This makes it easier to create new classes in future. The void *dummyTrain stuff is a bit clunky. I don't know if there's a more elegant way to defer construction of the map until runtime. Tom Bradley wrote:
class Base { .... }
class Train : public Base { ... static Train * create() { return new Train; } ... };
class Car : public Base { ... static Car * create() { return new Car; } ... };
int main() { map funcs<string, void (*create)()>; //these functions must be register into the map, but only once funcs["train"] = Train::create; funcs["car"] = Car::create
vehicle = funcs["car"](); //returns a pointer to a car }
-- JDL Non enim propter gloriam, diuicias aut honores pugnamus set propter libertatem solummodo quam Nemo bonus nisi simul cum vita amittit.