Home Segments Index Top Previous Next

649: Mainline

You might think that the deletion of a railroad car in the train array would activate the appropriate engine, box car, tank car, or caboose destructor. As usual, however, C++ ordinarily does not note whether the objects in the train array, defined to be full of railroad_car objects, belong to a more specific railroad-car type. To force C++ to take into account more specific type information, you must, once again, invoke the virtual-function mechanism, this time on the destructor for the railroad_car class, by placing the symbol virtual before the destructor definition:

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:                                          
          virtual ~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;} 
}; 

By making the railroad_car destructor virtual, you tell C++ to treat all the lower-level destructors as virtual. Thus, a virtual destructor exposes destructors in derived classes.