All pastes #175393 Raw Edit

Anonymous

public cpp v1 · immutable
·published 2006-09-18 19:20 UTC
rendered paste body
/*OUTPUT------Creating P: Making a polymorph...Creating polymorph bits* Something hijacks the polymorph factory *Creating Q: Making a something...Creating polymorph bitsCreating something bitsDestroying P: Destroying polymorph bitsDone :|Destroying Q: Destroying something bitsDestroying polymorph bitsDone :|*/#include <cstdio>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<CPolymorph*> (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 :|");}