Home Segments Index Top Previous Next

541: Mainline

After installing these definitions, and appropriate definitions for engines, tank cars, and cabooses, you can use the following for loop:

for (n = 0; n < car_count; ++n) { 
  // Display short name and capacity and terminate the line:  
  cout << train[n] -> short_name ( ); 
       << "     " 
       << train[n] -> capacity ( ) 
       << endl; 
} 

Using this for loop, the latest version of the analyze_train program is as follows:

#include   
const double pi = 3.14159; 
// Box, cylinder, and railroad car definitions go here 
class box_car : public railroad_car, public box { 
  public: box_car ( ) : box (10.5, 9.5, 40.0) { } 
          virtual char* short_name ( ) {return "box";} 
          virtual double capacity ( ) {return volume ( );} 
}; 
class tank_car : public railroad_car, public cylinder { 
  public: tank_car ( ) : cylinder (3.5, 40.0) { } 
          virtual char* short_name ( ) {return "tnk";} 
          virtual double capacity ( ) {return volume ( );} 
}; 
// Engine and caboose definitions go here 
// Define railroad car pointer array: 
railroad_car *train[100]; 
// Declare enumeration constants, needed in switch statement: 
enum {eng_code, box_code, tnk_code, cab_code}; 
main ( ) { 
  // Declare various integer variables: 
  int n, car_count, type_code; 
  // Read type number and create car class objects: 
  for (car_count = 0; cin >> type_code; ++car_count) 
    switch (type_code) { 
      case eng_code: train[car_count] = new engine;   break; 
      case box_code: train[car_count] = new box_car;  break; 
      case tnk_code: train[car_count] = new tank_car; break; 
      case cab_code: train[car_count] = new caboose;  break; 
    } 
  // Display report: 
  for (n = 0; n < car_count; ++n)  
    // Display short name and capacity and terminate the line:  
    cout << train[n] -> short_name ( ) 
         << "     " 
         << train[n] -> capacity ( ) 
         << endl; 
} 
--- Data ---
0 1 1 2 3 
--- Result --- 
eng     0 
box     3990 
box     3990 
tnk     1539.38 
cab     0 

Note that there is one small difference between this report and the one produced in Segment 509: zeros are displayed, rather than nothing, for the capacities of engines and cabooses.