Write a base class called Rectangle, which has two private member variables leng
ID: 656589 • 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
simple c++ shorten the code please
Explanation / Answer
/*
* File: main.cpp
* Author: Sravan Yadav E
*
* Created on October 28, 2014, 5:16 PM
*/
#include <cstdlib>
#include<iostream>
using namespace std;
class Rectangle
{
protected:
double length;
double width;
public:
double area;
Rectangle()
{
cout<<"Enter length:"<<endl;
cin>>length;
cout<<"Enter width:"<<endl;
cin>>width;
}
void calcAreaRectangle()
{
area=length*width;
}
void printRectangle()
{
cout<<"Area of rectangle: "<<area<<endl;
}
};
// Derived class
class Square: public Rectangle
{
public:
Square(): Rectangle()
{
calcAreaRectangle();
cout<<"Enter side for square: "<<endl;
cin>>Rectangle::length;
}
void calcAreaSquare()
{
area=length*length;
}
void printSquare()
{
cout<<"Area of square: "<<area<<endl;
}
};
int main(void)
{
Square s;
s.printRectangle();
s.calcAreaSquare();
s.printSquare();
return 0;
}
Output:
Enter length:
4
Enter width:
5
Enter side for square:
6
Area of rectangle: 20
Area of square: 36
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.