Suppose that you decide to count the number of cars whose serial number
begins with the three characters, NYC
.
One approach would be to determine whether each railroad car has such a
number by way of a member function defined in the railroad_car
class.
Imagine, however, that you have no access to the railroad_car
source
code, so you are prevented from adding any member functions. You could try,
nevertheless, to achieve your objective by defining an ordinary function,
check_owner
, that takes a railroad-car argument and character-string
argument:
Dereferenced train pointer, a railroad car object | | A string to compare to the serial number | | v v ----------- ----- check_owner (*(train[n]), "NYC")
Once check_owner
is defined, you can write statements
that run check_owner
over all the cars; increment a variable,
nyc_count
, whenever appropriate; and display a result:
int nyc_count = 0; for (n = 0; n < car_count; ++n) if (check_owner (*(train[n]), "NYC")) ++nyc_count; cout << "There are " << nyc_count << "NYC cars." << endl;