Home Segments Index Top Previous Next

164: Mainline

Now you can rewrite the program in Segment 155 with one version of volume defined as a member function of the box_car class and another version defined as a member function of the tank_car class. C++ picks the right function on the basis of the class-object argument.

#include 
const double pi = 3.14159;
class box_car {
  public: double height, width, length;
          double volume ( ) {                      
            return height * width * length;        
          }                                        
};
class tank_car {
  public: double radius, length;
          double volume ( ) {                      
            return pi * radius * radius * length;  
          }                                        
}; 
main ( ) { 
  box_car x; x.height = 10.5; x.width = 9.5; x.length = 40.0; 
  tank_car y; y.radius = 3.5; y.length = 40.0; 
  cout << "The volume of the box_car is " << x.volume ( ) << endl 
       << "The volume of the tank_car is " << y.volume ( ) << endl; 
} 
--- Result --- 
The volume of the box_car is 3990 
The volume of the tank_car is 1539.38