< Previous | Contents | Next >
One problem that can occur when a data member of an object points to a value on the heap is a memory leak. That’s because when the object is deleted, the pointer to the heap value disappears along with it. If the heap value remains, it produces a memory leak. To avoid a memory leak, the object should clean up after itself before it is destroyed by deleting its associated heap value. Fortu- nately, there’s a member function, the destructor, that’s called just before an object is destroyed, which can be used to perform the necessary cleanup.
A default destructor, which is created for you by the compiler if you don’t write your own, doesn’t attempt to free any memory on the heap that a data member might point to. This behavior is usually fine for simple classes, but when you have a class with data members that point to values on the heap, you should write your own destructor so you can free the memory on the heap associated with an object before the object disappears, avoiding a memory leak. That’s what I do in the Critter class. First, inside the class definition, I declare the destructor. Notice that a destructor has the name of the class preceded by ~ (the tilde character) and does not have any parameters or return a value.
Critter::~Critter() //destructor definition
{
cout << "Destructor called\n"; delete m_pName;
}
In main(), I put the destructor to the test when I call testDestructor(). The function creates a Critter object, toDestroy, and invokes its Greet() method, which displays I’m Rover and I’m 3 years old. &m_pName: 73F2ED48003AF644. The message provides a way to see the values of the object’s m_Age data member and the string pointed to by its m_pName data member. But it also displays the address of the string on the heap stored in the pointer m_pName. The important thing to
Working with Data Members and the Heap 309
note is that after the Greet() message is displayed, the function ends and toDestroy is ready to be destroyed. Fortunately, toDestroy’s destructor is automatically called just before this happens. The destructor displays Destructor called and deletes the string object equal to "Rover" that’s on the heap, cleaning up after itself and leaking no memory. The destructor doesn’t do anything with the m_Age data member. That’s perfectly fine since m_Age isn’t on the heap, but part of toDestroy and will be properly disposed of right along with the rest of the Critter object.
Hin t
When you have a class that allocates memory on the heap, you should write a destructor that cleans up and frees that memory.