Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a base class called Rectangle, which has two private member variables leng

ID: 3694539 • Letter: W

Question

Write a base class called Rectangle, which has two private member variables length and width. Write a constructor functions to set the values of width and length of the rectangle and also a function called area, where you calculate the area of the rectangle. Next derive a class called Square from Rectangle. Note that square has no member variable rather it uses the member variable from base class rectangle. Write constructor for this class and also provide a function called areaSquare to calculate area of square

Explanation / Answer


#include <iostream>
using namespace std;

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0)
      {
        Shape(a, b);
      }
      int area ()
      {
         cout << "Rectangle class area :" <<endl;
         return (width * height);
      }
};
class Square: public Shape{
   public:
      Square( int a=0, int b=0)
      {
        Shape(a, b);
      }
      int area ()
      {
         cout << "Square class area :" <<endl;
         return (width * height / 2);
      }
};
// Main function for the program
int main( )
{
   Shape *shape;
   Rectangle rec(10,7);
   Square Squ(10,5);

   // store the address of Rectangle
   shape = &rec;
   // call rectangle area.
   shape->area();

   // store the address of Square
   shape = &Squ;
   // call Squ area.
   shape->area();
  
   return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote