TITLE: template-based clone function (Source: comp.lang.c++.moderated, 13 Mar 2001 TROM: > class One > { > public: > virtual void Function(void) > { > cout<<"Function One"< } > > virtual One *Create(void) > { > return new One; > } > };//class One > > class Two : public One > { > public: > virtual void Function(void) > { > cout<<"Function Two"< } > };//class Two > [...] > > I'd like to use a 'Create' function in the base class (class One) that > I could use with all the derived classes (like class Two). Is possible > without I must to repeat the same code in all the classes?? > > The solution I don't like is: > > class Two : public One > { > public: > virtual void Function(void) > { > cout<<"Function Two"< } > > virtual One *Create(void) > { > return new Two; > } > };//class Two MENZL: "Gerhard Menzl" So what you want is a polymorphical function that default-constructs another instance of the derived class your base class pointer is pointing to, but you don't want to retype "return new " in every derived class, right? An unusual design - are you sure you don't want to clone the orginal? - but it can easily be achieved anyway using Jim Coplien's Curiously recurring template pattern: class Base { public: virtual Base* Create () = 0; // keep non-leaf classes abstract }; template class Creator : public Base { public: virtual Base* Create () { return new T; } }; class Derived : public Creator { //... }; This effectively creates an intermediary class between Base and every derived class that performs the creation work. That is, you still need separate creation code for every derived class, but you only have to type it once, and the compiler will generate all those repetitive new-expressions for you. Is that what you were looking for? _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com