Path: utzoo!attcan!uunet!aplcen!haven!ncifcrf!lhc!nih-csl!sparkler.dcrt.nih.gov!kgorlen From: kgorlen@sparkler.dcrt.nih.gov (Keith Gorlen) Newsgroups: comp.lang.c++ Subject: Re: Copying objects Keywords: Object copy constructor Message-ID: <210@nih-csl.nih.gov> Date: 27 Jun 90 19:43:36 GMT References: <18753@well.sf.ca.us> Sender: news@nih-csl.nih.gov Reply-To: kgorlen@sparkler.dcrt.nih.gov (Keith Gorlen) Distribution: comp Lines: 35 In article <18753@well.sf.ca.us>, mccarthy@well.sf.ca.us (Patrick McCarthy) writes: |>Given a pointer to a base type, what is the best way to copy the object |>pointed to (bearing in mind that it may actually point to an object of a |>derived type)? You might take a look at how the NIH Class Library implements the shallowCopy() and deepCopy() member functions. Basically, each class X defines the virtual function Object* X::shallowCopy() const { return new X(*this); } which will create a shallow copy of an X object by using the copy constructor for class X. Object::deepCopy() is a non-virtual member function that first uses shallowCopy() to make a shallow copy of an object, then invokes the virtual member function deepenShallowCopy(). Each class that has member variables that are pointers to objects or class instances implements deepenShallowCopy() to convert the shallow copy to a deep copy by applying deepenShallowCopy() recursively to the pointers and objects it contains. All this is described in detail in Section 7.3 of our new book "Data Abstraction and Object-Oriented Programming in C++", John Wiley & Sons, ISBN 047192346X. (I understand the first copies are probably running off the presses as I type.) The software is available via anonymous FTP in the file pub/nihcl.tar.Z on host alw.nih.gov (128.231.128.251). Keith Gorlen phone: (301) 496-1111 Building 12A, Room 2033 uucp: uunet!nih-csl!kgorlen National Institutes of Health Internet: kgorlen@alw.nih.gov Bethesda, MD 20892