Develop a C++ program using dynamic objects to calculate the area of triangle. (Dynamic Objects and Run Time Polymorphism)
#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;
}
Comments
Leave a comment