Pointers/Memory Allocation   «Prev  Next»
Lesson 14 Dynamic multidimensional arrays
Objective The deallocate() function

Purpose of C++ deallocate() Function

Examine the array deallocation function.

The deallocate() function in our dynamic, multidimensional array program deallocates the storage allocated by the operator new.

void deallocate(twod& m){
  for (int i = 0; i < m.column_size; ++i)
     delete [] m.base[i];
  delete [] m.base;
  m.row_size = 0;
  m.column_size = 0;
}

Deallocation works in reverse order to allocation. Each row is deallocated using delete []. It would be a mistake to deallocate m.base first, resulting in a system-dependent error. Only after each row of doubles is returned to free store can the column of pointers represented by m.base be safely deleted.
Next, we will look at the function that determines the maximum element of the array.

Why a destructor is needed

There are many reasons why a destructor may be needed. For example, an object may need to deallocate memory that it had previously allocated or it may need to close a file that it had opened. In C++, it is the destructor that handles deactivation events. The destructor has the same name as the constructor, but it is preceded by a ~. For example, here is the stack class and its constructor and destructor.

// This creates the class stack.
class stack {
int stck[SIZE];
int tos;
public:
stack(); // constructor
~stack(); // destructor
void push(int i);
int pop();
};
// stack's constructor
stack::stack()
{
tos = 0;
cout <<  "Stack Initialized\n";
}
// stack's destructor
stack::~stack()
{
cout <<  "Stack Destroyed\n";
}

Notice that, like constructors, destructors do not have return values.