fork download
  1. // Ex7_04.cpp
  2. // Using a constructor
  3. #include <iostream>
  4. using std::cout;
  5. using std::endl;
  6. class CBox // Class definition at global scope
  7. {
  8. public:
  9. double m_Length; // Length of a box in inches
  10. double m_Width; // Width of a box in inches
  11. double m_Height; // Height of a box in inches
  12.  
  13. // Constructor definition
  14. CBox(double lv, double wv, double hv)
  15. {
  16. cout << "Constructor called for CBox(" << lv << ','
  17. << wv << ',' << hv << ")." << endl;
  18. m_Length = lv; // Set values of
  19. m_Width = wv; // data members
  20. m_Height = hv;
  21. }
  22.  
  23. // Function to calculate the volume of a box
  24. double Volume()
  25. {
  26. return m_Length* m_Width* m_Height;
  27. }
  28.  
  29. };
  30.  
  31. int main()
  32. {
  33. CBox box1( 78.0, 24.0, 18.0 ); // Declare and initialize box1
  34. CBox cigarBox( 8.0, 5.0, 1.0 ); // Declare and initialize cigarBox
  35.  
  36. cout << "Volume of box1 = " << box1.Volume() << endl;
  37. cout << "Volume of cigarBox = " << cigarBox.Volume() << endl;
  38. return 0;
  39. }
Success #stdin #stdout 0s 5304KB
stdin
Standard input is empty
stdout
Constructor called for CBox(78,24,18).
Constructor called for CBox(8,5,1).
Volume of box1 = 33696
Volume of cigarBox = 40