Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!samsung!sdd.hp.com!zaphod.mps.ohio-state.edu!brutus.cs.uiuc.edu!apple!vsi1!octopus!sjsumcs!horstman From: horstman@sjsumcs.sjsu.edu (Cay Horstmann) Newsgroups: comp.lang.c++ Subject: Re: Cloning derived classes Keywords: inheritance, cloning, derived class Message-ID: <1990May5.160456.13542@sjsumcs.sjsu.edu> Date: 5 May 90 16:04:56 GMT References: <1019@rna.UUCP> Reply-To: horstman@sjsumcs.SJSU.EDU (Cay Horstmann) Organization: San Jose State University Lines: 17 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. > That appears to be a very dangerous thing to do in general. Many classes need more than bitwise copying for correct behavior (e.g. when using ref counts.) What if someone derives from your stuff, faithfully supplies the size function and adds a data member with nontrivial copy semantics? Cay