Home Segments Index Top Previous Next

460: Mainline

Bringing together both the modified class definitions and the modified definition of main, you have the following:

#include 
class railroad_car {
  public: railroad_car ( ) { }
          virtual void display_short_name ( ) {cout << "rrc";}  
};
class box_car : public railroad_car {
  public: box_car ( ) { }
          virtual void display_short_name ( ) {cout << "box";}  
};
// Similar definitions of tank_car, engine, and caboose go here
// Define railroad car pointer array:
railroad_car *train[100];
main ( ) {
  // Declare various integer variables:
  int n, car_count, type_code;
  // Read car-type number and create car class objects:
  for (car_count = 0; cin >> type_code; ++car_count)
    if (type_code == 0)        train[car_count] = new engine;
    else if (type_code == 1)   train[car_count] = new box_car;
    else if (type_code == 2)   train[car_count] = new tank_car;
    else if (type_code == 3)   train[car_count] = new caboose;
  // Display classes using display_short_name virtual function: 
  for (n = 0; n < car_count; ++n)                               
    {train[n] -> display_short_name ( ); cout << endl;}         
} 
--- Data ---
0 1 1 2 3 
--- Result --- 
eng 
box 
box 
tnk 
cab