Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!carson.berkeley.edu!jbuck From: jbuck@carson.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++ Subject: Re: Cloning derived classes Keywords: inheritance, cloning, derived class Message-ID: <35956@ucbvax.BERKELEY.EDU> Date: 2 May 90 19:42:29 GMT References: <1019@rna.UUCP> Sender: usenet@ucbvax.BERKELEY.EDU Reply-To: jbuck@carson.berkeley.edu (Joe Buck) Lines: 35 In article <1019@rna.UUCP>, kc@rna.UUCP (Kaare Christian) writes: > I recently needed to make a copy (a clone) of a class object, given only a > base class pointer to the object. C++ lets you do some things with a class, > knowing only its base type, but it doesn't provide an easy way to make > a copy. My solution was to make a virtual member function that > returned the size of each of the derived classes, and then make an > operator= function (left arg, ref pointer to base, right arg, ref to > base) that did the work - it called the size fn of the right operand to > determine how much space was needed, allocated it, did a bitwise copy, > then did some housekeeping. You're working too hard. All you really need to do is call the copy constructor from a virtual function. In the base class (I'll assume it's virtual) do class BaseType { virtual BaseType* copy () = 0; } For EACH derived class you must redefine the copy function, as follows. BaseType* DerivedType::copy () { return new DerivedType(*this); } If your BaseType isn't a virtual base class, then you'd define copy in the base class to return new BaseType(*this). This is simple; it calls the copy constructor for the appropriate type to do the copy. This assumes either that the default copy constructor will do, or that you've defined copy constructors when they won't. -- Joe Buck jbuck@ohm.berkeley.edu {uunet,ucbvax}!ohm.berkeley.edu!jbuck