[comp.lang.c++] How do you copy a Derived object?

ahodgson@athena.mit.edu (Antony Hodgson) (03/26/91)

Suppose I have a function, void f( Base& b ), and inside f() I want to
make a local copy of whatever b is.  Since b could actually be a derived
class, I can't simply do the following:

void f( Base& b )
    {	Base B(b);  ...  }

nor can I do

void f( Base& b )
    {   Base* B = new Base( b ); ...  }

What I really need to do is something like Base* B = new (typeof(b))(b).
Is this possible?  Thanks in advance for any help.  Email replies are fine.

Tony Hodgson
ahodgson@hstbme.mit.edu

dsr@mir.mitre.org (Douglas S. Rand) (03/27/91)

In article <1991Mar26.152847.5853@athena.mit.edu>, ahodgson@athena.mit.edu (Antony Hodgson) writes:
> 
> Suppose I have a function, void f( Base& b ), and inside f() I want to
> make a local copy of whatever b is.  Since b could actually be a derived
> class, I can't simply do the following:
> 
> void f( Base& b )
>     {	Base B(b);  ...  }
> 
> nor can I do
> 
> void f( Base& b )
>     {   Base* B = new Base( b ); ...  }
> 
> What I really need to do is something like Base* B = new (typeof(b))(b).
> Is this possible?  Thanks in advance for any help.  Email replies are fine.
> 
> Tony Hodgson
> ahodgson@hstbme.mit.edu
> 
> 

You can't do it that way.  There is no direct runtime information about the
class and copying is a sticky point anyway since different people mean
different things (for example: deep copy and shallow copy).  What you can
do is define a virtual copier for each class which allocates a new instance
and copies all the interesting pieces:

virtual Foobarclass:copier(Base& ob) {
	return(new Foobarclass((Foobarclass&) ob));
}

Where you have defined Foobarclass(Foobarclass&).  

There are no reasonable automatic semantics for copy.

-- 
Douglas S. Rand 
Internet:   <dsrand@mitre.org>
Snail:	    MITRE, Burlington Road, Bedford, MA 
Disclaimer: MITRE might agree with me - then again...
Amateur Radio: KC1KJ

philipps@zwsbdf.uucp (Christian Philipps) (04/12/91)

In article <1991Mar26.152847.5853@athena.mit.edu>, ahodgson@athena.mit.edu (Antony Hodgson) writes:
> 
> Suppose I have a function, void f( Base& b ), and inside f() I want to
> make a local copy of whatever b is.  Since b could actually be a derived
> class....

You need a deep clone mechanism, supported by the object itself. This
basically means, the object, and whatever object possibly hidden inside
or stored inside the object to be copied, must be able to clone itself
and return a pointer to the clone. This is similar to fork(), but some-
what more complicated.
As far as I remember, ET++ supports deep cloning of complex objects. I
don't know, however, how they did it exactly.

If you have access to a machine supporting file-names longer than 14 char-
acters, you'd best get a copy of ET++ (it's for free). The authors work
at the Union Bank of Switzerland.

c.u.
  Christian