• Source
    1. //C++ Derived Class Program
    2. /* Instructions:
    3. Create a “base class” that contains two protected variables and three public functions (input,
    4. calculate, and output). The “base class” inputs required data and calculates area for the
    5. rectangle.
    6. Create a “derived class” that contains one protected variable and three public functions (input,
    7. calculate, and output). The” derived class” MUST use the length and width data values in the
    8. “base class” to calculate the volume of the cube.
    9. Write a “main()” function that demonstrates the use of the classes and their functions.
    10. */
    11.  
    12. #include <iostream>
    13. using namespace std;
    14.  
    15. class Rectangle
    16. {
    17. protected:
    18. int length,
    19. width;
    20. public:
    21. void input(double length, double width)
    22. {
    23. /*Using the "this" pointer to access of members of the object
    24.   class, letting us define the protected variables */
    25. this->length = length;
    26. this->width = width;
    27. }
    28. int calculate()
    29. {
    30. return length * width;
    31. }
    32. void output()
    33. {
    34. cout << "*** RECTANGLE DATA ***" << endl;
    35. cout << "Length is " << length << endl;
    36. cout << "Width is " << width << endl;
    37. cout << "Area of the rectangle is " << this->calculate();
    38. }
    39. };
    40. //Cube is the derived class, rectangle is the base class
    41. //Derived class Cube contains all members of the base class, such as width
    42. class Cube: public Rectangle
    43. {
    44. protected:
    45. int height;
    46. public:
    47. void input(int height)
    48. {
    49. this->height = height;
    50. }
    51. int calculate()
    52. {
    53. return height*width*length;
    54. }
    55. void output()
    56. {
    57. cout << "*** CUBE DATA ***" << endl;
    58. cout << "Length is " << length << endl;
    59. cout << "Width is " << width << endl;
    60. cout << "Height is " << height << endl;
    61. cout << "Volume is " << this->calculate();
    62. }
    63. };
    64.  
    65. int main() {
    66. cout << "This program calculates the area of a rectangle\nand "
    67. << "the volume of a cube.\n\n";
    68. int len, wid, hgt;
    69. //Create a Cube object to use all three variables
    70. Cube myShape;
    71. cout << "Enter length: ";
    72. cin >> len;
    73. cout << "Enter width: ";
    74. cin >> wid;
    75. cout << "Enter height: ";
    76. cin >> hgt;
    77. //Use object.Class::method() to access the classes methods
    78. myShape.Rectangle::input(len, wid);
    79. cout << "\n\n";
    80. myShape.Rectangle::output();
    81. myShape.Cube::input(hgt);
    82. cout << "\n\n\n";
    83. myShape.Cube::output();
    84. cout << "\n\n\n\n";
    85. //system("pause");
    86. return 0;
    87. }
    88.