Answer to Question #182314 in C++ for Vijay Raj

Question #182314

Develop a C++ program using dynamic objects to calculate the area of triangle. (Dynamic Objects and Run Time Polymorphism)


1
Expert's answer
2021-04-18T13:52:18-0400
#include <iostream>

struct Shape {
    virtual ~Shape() = default;
    virtual float area() const noexcept = 0;
};

struct Triangle : public Shape {
    int height;
    int base;
    
    float area() const noexcept override {
        return height * base / 2.f;
    }
};

int main() {
    Triangle triangles[2] = {};
    triangles[0].height = 5;
    triangles[0].base = 10;
    triangles[1].height = 8;
    triangles[1].base = 12;
    Shape* shapes[2] = { &triangles[0], &triangles[1] };

    size_t i = 0;
    for(auto x : shapes) {
        std::cout << "Area of triangle " << i << " is " << x->area() << '\n';
        i++;
    }
    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