Home Segments Index Top Previous Next

647: Mainline

To reclaim the memory in a class-object character array, you take advantage of what are called destructor functions, which are member functions that run when the memory for a class object is reclaimed.

Like that of a constructor, the name of the destructor is based on the name of the class, but unlike the constructor name, the destructor name includes a tilde prefix. The following, for example, is the railroad_car class, augmented with a destructor that reclaims memory from the serial_number array:

class railroad_car {
  public: char *serial_number;
          // Constructors:
          railroad_car ( ) { }
          railroad_car (char *input_buffer) {
            // Create new array just long enough:
            serial_number = new char[strlen(input_buffer) + 1];
            // Copy string into new array:
            strcpy (serial_number, input_buffer);
          }
          // Destructor:                                          
          ~railroad_car ( ) {                                     
            cout << "Deleting a railroad serial number" << endl;  
            delete [ ] serial_number;                             
          }                                                       
          // Other: 
          virtual char* short_name ( ) {return "rrc";} 
          virtual double capacity ( ) {return 0.0;} 
}; 

Note that, when you use the delete operator to reclaim an array of objects, rather than an individual object, you place two brackets, [ ], between the delete operator and the array name. Because C++ keeps track of the lengths of all arrays created by the new operator, C++ can proceed to reclaim all the memory in such an array.