rectangle

Write C++ implementation code for the following scenario.

  • Define a base class Shape and a child class Rectangle to implement inheritance. Rectangle class will have set_data, get_data and print_area as member functions.
  • Define a friend function “getcordinates” to the class Rectangle which will access & print values of private data members of the Rectangle class as output when called in main().
  • Overload ‘+’ operator for Rectangle class and create an object R3 with its length and width equal to sum of R1 and R2. At the end display the length, width and area of newly created R3 object.

 

#include<iostream>
using namespace std;
class shape {
    public:
        void set_data();
        void get_data();
        void print_area();
};

class rectangle : public shape {
    private:
        float length, width;
    public:
        void set_data()
        {
            cout<<endl<<endl<<"Enter Length of rectangle: ";
            cin>>length;
            cout<<"Enter Width of rectangle: ";
            cin>>width;
        }
        void get_data()
        {
            cout<<"Length: "<<length<<endl<<"Witdh:"<<width;
        }
        void print_area()
        {
            float area = length * width;
            cout<<endl<<"Area of rectangle is: "<<area;
        }
        
        // Overload ‘+’ operator for Rectangle class
        rectangle operator+(const rectangle& r1)
        {
            rectangle r3;
            r3.length = this->length + r1.length;
            r3.width = this->width + r1.width;
            return r3;
        }
};

// friend function “getcordinates”
void getcordinates(rectangle rec)
{
    rec.get_data();
}

int main()
{
    rectangle r1;
    r1.set_data();
    getcordinates(r1);
    r1.print_area();
    
    rectangle r2;
    r2.set_data();
    getcordinates(r2);
    r2.print_area();
    
    cout<<endl<<endl<<"Printing Details of R3"<<endl;
    rectangle r3 = r1 + r2;
    getcordinates(r3);
    r3.print_area();
    return 0;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *