Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!yale!cmcl2!rna!kc From: kc@rna.UUCP (Kaare Christian) Newsgroups: comp.lang.c++ Subject: Cloning derived classes Keywords: inheritance, cloning, derived class Message-ID: <1019@rna.UUCP> Date: 2 May 90 14:20:25 GMT Organization: Rockefeller University - Neurobiology Lines: 28 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. Shouldn't this be easier? Given a (base *) pointer to a derived object, I think it should be easy to make a copy of the thing pointed at. One way might be to add a clone facility, that would be used equivalently to new, but that would duplicate an existing object. 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 Kaare Christian kc@rna.rockefeller.edu