Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!cs.utexas.edu!helios!jadam From: jadam@cs.tamu.edu (James P Adam) Newsgroups: comp.lang.c++ Subject: Virtrual memory allocation Summary: Q: How to allocate for an object of unknown class or size Keywords: C++ memory allocation virtual Message-ID: <13476@helios.TAMU.EDU> Date: 19 Mar 91 19:35:05 GMT References: <23659@well.sf.ca.us> <1896@news.tcs.com> Sender: usenet@helios.TAMU.EDU Organization: Computer Science Department, Texas A&M University Lines: 53 In attempting to create some AI-type problem simulators (e.g., the 3 missionaries && 3 canibals problem), I've found myself with a memory allocation problem. First, here is a general outline of what is going on: 1) I have created a set of Position classes, all derived from an abstract class called Position. The derived classes can be numerous: e.g., OneDPos, TwoDPos, etc. The size of each derived class will be quite different from the size of other derived classes, and will certainly be different than the size of the virtual base class itself! 2) A different class, not derived from Position, will be called class Move, and this class will store two Position pointers: class Move { Position * From; Position * To; } 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. As far as I can tell, each of these options has its strengths and weaknesses. In #1 && #2, there is the danger than a derived class might "forget" to overload the operator, which would cause the inherited method to fire, which would undoubtably cause the wrong amount of memory to be allocated, which would then cause the program to become corrupt && work erroneously (but in a way that would be extremely difficult to track down). 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? Thanx: Jim