Answer to Question #214389 in C++ for shayan abbasi

Question #214389

Write a program having classes Rectangle with data member length and width ,square with data member side .Equalitrial Triangle with data member sides.All these classes are derived from class shape.Write an independent function which will exhibit polymorphism and show thr area of the object passed to the function.All the data memebers of class are private you can write suitable function needed for you


1
Expert's answer
2021-07-06T12:17:03-0400
#include <iostream>
using namespace std;
class Shape{
    public:
    Shape(){}
    virtual float area(){return 0;}
};
class Rectangle:public Shape{
    float length, width;
    public:
    Rectangle(): Shape(){}
    Rectangle(float l, float w): length(l), width(w), Shape(){}
    float area(){
        return length * width;
    }
};
class Square:public Shape{
    float side;
    public:
    Square():Shape(){}
    Square(float s):side(s), Shape(){}
    float area(){
        return side * side;
    }
};
class EquilateralTriangle:public Shape{
    float side;
    public:
    EquilateralTriangle(): Shape(){}
    EquilateralTriangle(float s): side(s), Shape(){}
    float area(){
        return 0.5 * side * side;
    }
};
template<typename object>
void showArea(object* Obj){
    cout<<Obj->area()<<endl;
}
int main(){
    Rectangle rect(5, 5);
    Square sq(5.5);
    EquilateralTriangle triangle(6);


    showArea<Rectangle>(&rect);
    showArea<Square>(&sq);
    showArea<EquilateralTriangle>(&triangle);


    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