Home Segments Index Top Previous Next

239: Mainline

Thus, when your program creates a box_car object, the default box_car constructor is called, as well as the default constructors for the railroad_car, box, and container classes, as demonstrated by the output statements placed in the default constructors:

#include  
int current_year = 2001; 
const double pi = 3.14159; 
class container { 
  public: int percent_loaded; 
          container ( ) { 
            cout << "Calling container default constructor." << endl; 
          } 
}; 
class box : public container { 
  public: double height, width, length; 
          box ( ) { 
            cout << "Calling box default constructor." << endl; 
          } 
          double volume ( ) { 
            return height * width * length; 
          } 
}; 
// Cylinder definition goes here 
class railroad_car { 
  public: int year_built; 
          railroad_car ( ) { 
            cout << "Calling railroad_car default constructor." 
                 << endl; 
          } 
          int age ( ) {return current_year - year_built;} 
}; 
class box_car : public railroad_car, public box { 
  public: box_car ( ) { 
            cout << "Calling box_car default constructor." << endl; 
            height = 10.5; width = 9.2; length = 40.0;} 
}; 
// Other railroad car class definitions go here 
main ( ) { 
  box_car b;                // Construct a box car 
  b.year_built = 1943;      // Specify when it was built 
  b.percent_loaded = 66;    // Specify how full it is 
  // Display age using a railroad_car member function: 
  cout << "The car is " << b.age ( ) << " years old." << endl; 
  // Display how full using a container member variable: 
  cout << "And " << b.percent_loaded << " percent loaded." << endl; 
  // Display volume using a box member function: 
  cout << "Its volume is " << b.volume ( ) << " units." << endl; 
} 
--- Result --- 
Calling railroad_car default constructor. 
Calling container default constructor. 
Calling box default constructor. 
Calling box_car default constructor. 
The car is 58 years old. 
And 66 percent loaded. 
Its volume is 3864 units.