Newsgroups: comp.lang.c++ Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!sdd.hp.com!elroy.jpl.nasa.gov!decwrl!fernwood!lia!jgro From: jgro@lia (Jeremy Grodberg) Subject: Re: Virtrual memory allocation Message-ID: <1991Mar20.224829.2611@lia> Reply-To: jgro@lia.com (Jeremy Grodberg) References: <23659@well.sf.ca.us> <1896@news.tcs.com> <13476@helios.TAMU.EDU> Date: Wed, 20 Mar 91 22:48:29 GMT In article <13476@helios.TAMU.EDU> jadam@cs.tamu.edu (James P Adam) writes: >[How do I create new objects of derived types given only their base class > references?]. > The problem I am having is in the constructors for class Move. My >basic desire is to allocate space inside these constructors to hold >objects of class Position. What I originally tried to do was: > Move::Move( Position& newFrom, Position& newTo ) > { > From = new( newFrom ); // error checking removed... > To = new( newTo ); // ...for the sake of simplicity > } > The compiler doesn't like this, and I can commiserate with it. >Obviously, I can't say something like "From = new( Position )", since >I don't want sizeof( class Position) bytes, I want enough memory >to hold the (unknown) class that's being passed in. > Three suggestions have been made to me for solving this problem. > 1) Overload the new operator. I'm not really sure how this would >solve my problem, unless I'm supposed to say something like >"From = newFrom.new()", and create a virtual new operator for each class. > 2) Create a sizeOf() operator for each class, which would work as follows: >"From = new( newFrom.sizeOf() )". > 3) Force the calling process to allocate the space && simply copy a >pointer in Move's constructor. > > [...] > > Option #3 is weak because it requires the "user" programmer to >properly allocate objects prior to each call to a Move constructor. > Is there an approved-of, or philosophically sound, way of >accomplishing what I am trying to do? The method which I like best, and which seems to raise the fewest objections, is to create a virtual method called clone() in your base class (Position), which returns a copy of the object. Yes, you must override it everywhere, but if you forget, you just get the base class part, instead of a core dump (although to some people this is not an advantage). Unfortunately, as with asking an object for its type, there is no way in C++ to have the compiler do all the work for you; you will have to rely on programming everything correctly. Clone(), however, is trivial enough that if you remember to do it at all, you will do it right. -- Jeremy Grodberg "Show me a new widget that's bug-free, and I'll show jgro@lia.com you something that's been through several releases."