LearnFrenzy
Sign in Take a free test

OOPS Concepts · OOPS Programs · Question 3

Shape hierarchy with virtual area and perimeter in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Create an abstract Shape class with pure virtual area, perimeter and name, implement Circle, Rectangle and Triangle, print a table for a vector of shapes, and report the largest one.

Solution
main.cpp
#include <cmath>
#include <format>
#include <iostream>
#include <memory>
#include <numbers>
#include <string>
#include <vector>

class Shape {
public:
    virtual double area() const = 0;
    virtual double perimeter() const = 0;
    virtual std::string name() const = 0;
    virtual ~Shape() = default;
};

class Circle : public Shape {
    double r_;
public:
    explicit Circle(double r) : r_(r) {}
    double area() const override { return std::numbers::pi * r_ * r_; }
    double perimeter() const override { return 2 * std::numbers::pi * r_; }
    std::string name() const override { return "Circle"; }
};

class Rectangle : public Shape {
    double w_, h_;
public:
    Rectangle(double w, double h) : w_(w), h_(h) {}
    double area() const override { return w_ * h_; }
    double perimeter() const override { return 2 * (w_ + h_); }
    std::string name() const override { return "Rectangle"; }
};

class Triangle : public Shape {
    double a_, b_, c_;
public:
    Triangle(double a, double b, double c) : a_(a), b_(b), c_(c) {}
    double perimeter() const override { return a_ + b_ + c_; }
    double area() const override {
        double s = perimeter() / 2;
        return std::sqrt(s * (s - a_) * (s - b_) * (s - c_));
    }
    std::string name() const override { return "Triangle"; }
};

int main() {
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Circle>(2));
    shapes.push_back(std::make_unique<Rectangle>(3, 5));
    shapes.push_back(std::make_unique<Triangle>(6, 8, 10));
    const Shape* largest = nullptr;
    for (const auto& s : shapes) {
        std::cout << std::format("{:<10}{:>8.2f}{:>8.2f}\n", s->name(), s->area(), s->perimeter());
        if (!largest || s->area() > largest->area()) largest = s.get();
    }
    std::cout << "largest: " << largest->name() << '\n';
    return 0;
}

Output Verified by compiling and running

Circle       12.57   12.57
Rectangle    15.00   16.00
Triangle     24.00   24.00
largest: Triangle

The loop calls the same three virtual functions on every shape; each class supplies its own formula. A raw pointer is fine for "largest" because it only observes objects owned by the vector.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links