Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uwm.edu!rpi!zaphod.mps.ohio-state.edu!usc!apple!voder!procase!roger From: roger@procase.UUCP (Roger H. Scott) Newsgroups: comp.lang.c++ Subject: Re: Cloning derived classes Keywords: inheritance, cloning, derived class Message-ID: <138@logo.procase.UUCP> Date: 5 May 90 05:49:10 GMT References: <1019@rna.UUCP> Reply-To: roger@procase.UUCP (Roger H. Scott) Organization: proCASE Corporation, Santa Clara, CA Lines: 52 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. I suppose that depends almost entirely on how you define "easy". Do you mean something easier than the following?: class Base { public: Base(); Base(Base&); virtual Base *clone() {return new Base(*this);} }; class Derived : public Base { public: Derived(); Derived(Derived&); Base *clone() {return new Derived(*this); }; ... Base *p = ...; Base *another_just_like_p = p->clone(); >... >One way might be to add a clone facility, that would be used equivalently >to new, but that would duplicate an existing object. The problem here is the word "duplicate". It is rarely the case that a logical "clone" of an object is simply a bit-wise copy (a.k.a. shallow copy). Sometimes what you want is a clone of an entire structure (a.k.a deep copy). > Base *p = ... ; > Base *b; > b = clone *p; // new takes a type, clone takes an object > >Another method might be to have a typeof builtin, perhaps similar to the >following: > Base *p = .... ; > Base *b; > b = new typeof(*p); // allocates space > *(typeof(*p) *)b = *(typeof(*p) *)p; // ugly, but copies whole thing Both of these schemes suffer from the same problem: *in general*, a C++ compiler does not know the type of the object that a pointer points to. In order to fix this the definition of the language would have to be changed so that *all* objects were guaranteed to encode their own type in some manner or other. The fact that this is not so is not immediately obvious from the language definition (as opposed to from well-known implementations), but it can be inferred from the conformance of C++ structs to C structs and the equivalence of C++ classes to C++ structs. I.M.H.O. the biggest mistake made in the design of C++ was the equivalence of classes and structs.