#include #include #include #include using namespace std; //A pointer_t is a pointer to a function that dynamically allocates a new object //of a class derived from class base, and returns the address of the new object. class base; typedef base *(*pointer_t)(); class base { static map m; public: struct namer {namer(const string& s, pointer_t p) {base::m[s] = p;}}; friend namer::namer(const string& s, pointer_t p); static base *f(const string& s) {return m[s]();} virtual void print() const = 0; }; map base::m; class child1: public base { static base *alloc() {return new child1;} static namer n; public: void print() const {cout << "child1\n";} }; base::namer child1::n("child1", alloc); class child2: public base { static base *alloc() {return new child2;} static namer n; public: void print() const {cout << "child2\n";} }; base::namer child2::n("child2", alloc); class grandchild: public child2 { static base *alloc() {return new grandchild;} static namer n; public: void print() const {cout << "grandchild\n";} }; base::namer grandchild::n("grandchild", alloc); int main() { base *p = base::f("child1"); p->print(); delete p; p = base::f("child2"); p->print(); delete p; p = base::f("grandchild"); p->print(); delete p; return EXIT_SUCCESS; }