TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: Neil Heller
from: Darin McBride
date: 2003-09-08 10:42:10
subject: `new`ing pointers

Hello Neil!

Replying to a message of Neil Heller to All:

 NH> I'm working on a program that's got 2 classes:  #1 = a node class and
 NH> #2  = a linked_list class.  The node class looks like:

 NH> class Node {
 NH>      private:
 NH>           char * SomeString;   // length determined at run-time

 NH>      public:
 NH>           void SomeFunction();
void PrepareRoom(size_t length) { delete [] SomeString; SomeString = new
char[length]; }

 NH> };


 NH> class linked_list {
 NH>      private:
 NH>           Node * ANode;

 NH>      public:
 NH>           void build_it();
 NH> };


 NH> file:  linked_list.cpp

 NH> void  linked_list::build_it()
 NH> {
 NH>      ANode = new Node();

 NH> I'm OK so far, so now I compute just how much space I'll need for 
 NH> SomeString.  The question I have is - how can I allocate that space?  

Only Node can allocate the space you want.

 NH> ANode->SomeString = new char[CalculatedNumber];

 NH> This doesn't work in build_it() because SomeString is a private

This would be a bad thing to do because if you later changed Node's
implementation to use a C++ string internally, this code would have to
change, defeating the data hiding principles.

 NH> variable  in class Node.  In order to allocate the space, do I need
 NH> to declare  SomeString as protected?  Would deriving linked_list from
 NH> Node allow me  access to private variables in Node from linked_list?

The best bet, really, is that Node would allocate the space when it is
required to, but not any earlier, all automatically.  This would allow you
to rewrite Node to use other string objects later without changing anyone
else's code.

Darin

---
* Origin: Tanktalus' Tower BBS (1:250/102)
SEEN-BY: 633/267 270
@PATH: 250/102 99 10/345 106/1 2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.