Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sun-barr!apple!snorkelwacker.mit.edu!think.com!linus!linus!mir!dsr From: dsr@mir.mitre.org (Douglas S. Rand) Newsgroups: comp.lang.c++ Subject: Re: How do you copy a Derived object? Message-ID: <1991Mar26.175026.12955@linus.mitre.org> Date: 26 Mar 91 17:50:26 GMT References: <1991Mar26.152847.5853@athena.mit.edu> Sender: news@linus.mitre.org (News Service) Reply-To: dsr@mir.mitre.org (Douglas S. Rand) Organization: The MITRE Corporation Lines: 42 Nntp-Posting-Host: mir.mitre.org 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: Snail: MITRE, Burlington Road, Bedford, MA Disclaimer: MITRE might agree with me - then again... Amateur Radio: KC1KJ