Answer to Question #334819 in C++ for Ashutosh

Question #334819

Create a Class Shape having a field shapeType and a function printMyType.Create another class, Square and Rectangle, which inherits the Shape class and has additional fields length and breadth. Both Square and Rectangle classes will have two functions calculateArea, which will return the object's area, and printMyType, which will print the type of the object.Inside the main, first create the object of class Square and have a length equal to 5 and call the printMyType then calculateArea method after creating the object of class Rectangle having the length equal to 5 and breadth equal to 4 and again call the printMyType and calculateArea method.

1
Expert's answer
2022-04-28T13:21:53-0400
#include <iostream>
#include <string>
using namespace std;
//*****************************************
//      class Shape declaration           *
//*****************************************
class Shape {
public:
    void printMyType();
    string shapeType;    
};
void Shape::printMyType(){
    cout<<shapeType;
}
//*****************************************
//      class Rectangle declaration       *
//*****************************************
class Rectangle : public Shape {
private:
    double width;
    double height;

public:
    Rectangle(double w, double h)   {
        width=w;
        height=h;
          shapeType = "Rectangle";          
 }
    double calculateArea()     {
        return width * height;
    }
 };
//*****************************************
//      class Square declaration          *
//*****************************************
class  Square : public Shape {
private:
    double width;
    
public:
     Square(double w)   {
        width=w;
           shapeType = "Square";          
 }
    double calculateArea()     {
        return width * width;
    }
};
 
int main() {
  Rectangle rect1(4, 5);
 
  cout<<"Shape type: ";
  rect1.printMyType();
 
  cout<<endl;
 
  cout<<"Area: "<< rect1.calculateArea();
 
  cout<<endl;
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS