Path: utzoo!attcan!uunet!decwrl!apple!well!mccarthy From: mccarthy@well.sf.ca.us (Patrick McCarthy) Newsgroups: comp.lang.c++ Subject: Copying objects Keywords: Object copy constructor Message-ID: <18753@well.sf.ca.us> Date: 27 Jun 90 03:01:01 GMT Distribution: comp Lines: 32 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)? In other words, suppose you have a class called Base, and two classes Derived_1 and Derived_2 which inherit from Base. Suppose further that p and q are of type Base *. In order to make p point to a copy of q using q's copy constructor, you would have know q's type in advance as follows: p = (Base *) new Derived_2(q); I am searching for a solution which does not require knowlege of the type of the object being copied. The best way I can think of to do this is to define a virtual function, Base *Base::CloneSelf(), in the base class. This function would then be overridden by all inherited classes. The wierdism here is that in order to override the function, Derived_1::CloneSelf() would have to return a pointer of type Base *. It seems as though there should be a better way of doing this. Any and all suggestions are welcome (as long as they're _constructive_ - pun intended :-) Thanks! ------------------------------------------------------------------------ Pat McCarthy mccarthy@well.uucp ".signature? I ain't got to show you no stinking .signature!"