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

C2 -> Create a Rectangle class template that can store the lengths of the sides

ID: 3880569 • Letter: C

Question

C2 -> Create a Rectangle class template that can store the lengths of the sides (in the private section) as any datatype. Make class functions for setting the width and length of the rectangle. Make a function that will return 'true' if the length is greater than the width and 'false' otherwise. Make two other functions the will return the perimeter and area of the Rectangle.  Test the Rectangle class by using a float and a double. Don't worry about the Fraction type.

C3-> Add const specifiers and two constructors to the Rectangle class template. The first constructor passes in no parameter's and does nothing. The second constructor passes in the width and the length of the Rectangle.

Explanation / Answer

#include<iostream>
using namespace std;
template <typename T>
class Rectangle
{// template that can store the lengths of the sides (in the private section) as any datatype.
   private:
       T width;
       T length;
       //two constructors to the Rectangle class template. The first constructor passes in no parameter's and does nothing. The second constructor passes in the width and the length of the Rectangle.
   public:
   //constructors
   Rectangle()
   {
   //do nothing  
   }
   Rectangle(T x,T y)
   {
       width =x;
       length = y;  
   }
   //setter methods
   void set_width(T x)
   {
       width =x;
   }
   void set_length(T x)
   {
       length =x;  
   }
   //Make a function that will return 'true' if the length is greater than the width and 'false' otherwise.
   bool compare()
   {
       if(length>width)
       return true;//if length greater than width
       else return false;//other wise  
   }
   //perimeter
   T perimeter()
   {
       return 2*(length+width);  
   }
   //area
   T area()
   {
       return (width*length);  
   }
  
};
int main()
{
   //testing in main
   //Test the Rectangle class by using a float and a double
   Rectangle<float> *f = new Rectangle<float>(2,3);
   Rectangle<double> *d = new Rectangle<double>(3,5);
   cout<<f->perimeter()<<endl;
   cout<<f->area()<<endl;
   cout<<d->perimeter()<<endl;
   cout<<d->area()<<endl;
   f->set_width(3);
   f->set_length(5);
   d->set_width(2);
   d->set_length(3);
   cout<<f->perimeter()<<endl;
   cout<<f->area()<<endl;
   cout<<d->perimeter()<<endl;
   cout<<d->area()<<endl;
  
   return 0;
}

output:

10
6
16
15
16
15
10
6


Process exited normally.
Press any key to continue . . .

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