Using the specialized pattern, you can overload the output operator so that output statements can handle railroad-car operands, surrounding each car's short name with brackets:
ostream& operator<< (ostream& output_stream, railroad_car& r) { output_stream << "[" << r.short_name ( ) << "]"; return output_stream;}
Note that the parameter, r
, declared to be a
railroad_car
must be a call-by-reference parameter, because
you want the overloaded output operator to handle objects that
belong to subclasses of the railroad_car
class, such as
box_car
objects.
As you learned in Chapter 37, if r
were a call-by-value
parameter, and the argument were, say, a box_car
object, then
only that part of the object inherited from the railroad_car
class
would be copied, and there would be no way for the overloaded output
operator to know that [box]
, rather than [rrc]
, is supposed
to be displayed.