/* OUTPUT ------ Creating P: Making a polymorph... Creating polymorph bits * Something hijacks the polymorph factory * Creating Q: Making a something... Creating polymorph bits Creating something bits Destroying P: Destroying polymorph bits Done :| Destroying Q: Destroying something bits Destroying polymorph bits Done :| */ #include class CPolymorph { public: virtual ~CPolymorph () { puts ("Destroying polymorph bits"); }; static CPolymorph* create () { return (CPolymorph*) CPolymorph::finalConstructor(); }; protected: /* Prevent direct initiation */ CPolymorph () { puts("Creating polymorph bits"); }; /* Prevent copy construction and reference assignment */ CPolymorph (const CPolymorph&); CPolymorph& operator= (const CPolymorph&); /* static constructor */ static void* getBaseInterface () { puts ("Making a polymorph..."); return new CPolymorph(); }; /* virtual constructor pointer */ static void* (*finalConstructor)(); }; void* (*CPolymorph::finalConstructor)() = &CPolymorph::getBaseInterface; class CSomething : CPolymorph { public: CSomething () { puts ("Creating something bits"); }; ~CSomething () { puts ("Destroying something bits"); }; static void replaceBase() { CPolymorph::finalConstructor = &CSomething::getBaseInterface; }; protected: static void* getBaseInterface() { puts ("Making a something..."); return static_cast (new CSomething()); }; }; int main (int argc, char** argv) { puts ("Creating P: "); CPolymorph* p = CPolymorph::create (); puts ("\n* Something hijacks the polymorph factory *"); CSomething::replaceBase(); puts ("\nCreating Q: "); CPolymorph* q = CPolymorph::create (); puts ("\nDestroying P: "); delete p; puts ("Done :|"); puts ("Destroying Q: "); delete q; puts ("Done :|"); }