Home Segments Index Top Previous Next

454: Mainline

You might think that similar amendments to the engine, tank_car, and caboose classes would enable you to display car names using a for loop such as the following:

for (n = 0; n < car_count; ++n) { 
  train[n] -> display_short_name ( ); 
  cout << endl; 
} 

After all, train[n] picks a particular pointer out of the array, and the class-pointer operator, ->, tells C++ to go through the pointer to get at display_short_name, a member function defined in the definitions of all four car types.

Your C++ compiler rejects the program, nevertheless. The reason is that the train array is supposed to contain pointers to railroad_car objects, and you have defined no display_short_name function for railroad_car objects. At compile time, the compiler has no clue that the pointers in the train array may actually point to objects that belong to subclasses for which the display_short_name function is defined.