Home Segments Index Top Previous Next

221: Mainline

So far, you have learned how you can define classes for two railroad-car types: box cars and tank cars. Now suppose that you want to add information that is common to all railroad cars.

One way to proceed is to start with the classes that you have already defined for box cars and tank cars, adding whatever information you need. The following, for example, is one way to augment the box_car class:

int current_year = 2001; 
class box_car { 
  public: 
    // From a previous definition of the box_car class: 
    double height, width, length; 
    box_car ( ) {height = 10.5; width = 9.2; length = 40.0;} 
    double volume ( ) {return height * width * length;} 
    // New member variables: 
    int percentage_loaded; 
    int year_built; 
    // New member function; relies on current_year, a global variable: 
    int age ( ) {return current_year - year_built;} 
}; 

The problem with this way of defining railroad cars is that the percentage_loaded member variable would have to be repeated in both the box_car and tank_car class definitions, and the year_built member variable and the age member function would have to be repeated not only in those classes, but also in classes defined for, say, engine and caboose classes.