Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!usc!rutgers!bellcore!att!dptg!ulysses!andante!alice!shopiro From: shopiro@alice.UUCP (Jonathan Shopiro) Newsgroups: comp.lang.c++ Subject: Re: Variable sized objects Summary: C++ doesn't support variable sized objects. Use indirection. Message-ID: <10213@alice.UUCP> Date: 5 Dec 89 14:49:12 GMT References: <1020@dutrun.UUCP> Organization: AT&T Bell Laboratories, Murray Hill NJ Lines: 59 In article <1020@dutrun.UUCP>, ben@duttnph.tudelft.nl (Ben Verwer) writes: > How do you implement variable sized objects in 2.0 > Consider the example of a stack from Stroustrup, page 165: > > class char_stack { > int size; > char *top; > char s[1]; > public: > char_stack(int sz); > void push(char c) // etc... > char pop() // etc... > }; > > char_stack::char_stack(int sz) { > this = (char_stack*)new char[sizeof(char_stack)+sz-1]; > size = sz; > top = s; > } > > You can allocate a new stack by the statement: > char_stack* mystack = new char_stack(1000); > > In 2.0 operator new has be be used instead of assignment to this. Operator new is supplied to support controlling where memory is allocated for objects, not how much memory is allocated. The trick described in ``the book'' is non-portable, implementation-dependent, and generally a bad idea. Objects in C++ are always fixed-size. You can easily make objects _appear_ to be variable sized by using indirection, e.g., class Char_stack { int size; char* top; char* base; public: Char_stack(int); ~Char_stack(); // etc }; Char_stack::Char_stack(int sz) : size(sz) { base = top = new char[size]; } Char_stack::~Char_stack() { delete [size] base; } Similar techniques can be used to make an object into a surrogate for a linked structure such as a list or graph. By the way, there are two contributors to this list that match Jonathan Sh[ao]piro. The twain have met, and will probably meet again, but still hope not to be confused. -- Jonathan Shopiro AT&T Bell Laboratories, Warren, NJ 07060-0908 research!shopiro (201) 580-4229