Home Segments Index Top Previous Next

189: Mainline

A reader is a function that extracts information from an object. One reason that you may wish to use a reader, rather than referencing a member variable directly, is that you can include additional computation in a reader. For example, if you are concerned about how often your program references the radius member variable, you can add a statement to the read_radius reader that announces each reference:

class tank_car {
  public:
    double radius, length;
    tank_car ( ) {radius = 3.5; length = 40.0;}
    tank_car (double r, double l) {radius = r; length = l;}
    double read_radius ( ) {
      cout << "Reading a tank_car's radius ..." << endl;  
      return radius;} 
    double volume ( ) {return pi * radius * radius * length;} 
};