< Previous | Contents | Next >
To declare a data member that points to a value on the heap, you first need to declare a data member that’s a pointer. That’s just what I do in Critter with the following line, which declares m_pName as a pointer to a string object.
string* m_pName;
In the class constructor, you can allocate memory on the heap, assign a value to the memory, and then point a pointer data member to the memory. That’s what I do in the constructor definition with the following line, which allocates memory for a string object, assigns name to it, and points m_pName to that chunk of memory on the heap.
m_pName = new string(name);
I also declare a data member that is not a pointer:
int m_Age;
This data member gets its value in the constructor the way you’ve seen before, with a simple assignment statement:
m_Age = age;
You’ll see how each of these data members is treated differently as Critter
objects are destroyed, copied, and assigned to each other.
Now, the first object with a data member on the heap is created when main() calls testDestructor(). The object, toDestroy, has an m_pName data member that points to a string object equal to "Rover" that’s stored on the heap. Figure 9.7 provides a visual representation of the Critter object. Note that the image is abstract because the name of the critter is actually stored as a string object, not a string literal.
308 Chapter 9 n Advanced Classes and Dynamic Memory: Game Lobby
Figure 9.7
A representation of a Critter object. The string object equal to "Rover" is stored on the heap.