LearnFrenzy
Sign in Take a free test

OOPS Concepts · OOPS Programs · Question 2

Rectangle class with area, perimeter and comparison in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

Write a Rectangle class with a constructor that validates its sides, const member functions for area, perimeter and is_square, and compare two rectangles.

Solution
main.cpp
#include <iostream>
#include <stdexcept>

class Rectangle {
    double w_, h_;
public:
    Rectangle(double w, double h) : w_(w), h_(h) {
        if (w <= 0 || h <= 0) throw std::invalid_argument("sides must be positive");
    }
    double area() const { return w_ * h_; }
    double perimeter() const { return 2 * (w_ + h_); }
    bool is_square() const { return w_ == h_; }
    bool bigger_than(const Rectangle& o) const { return area() > o.area(); }
};

int main() {
    Rectangle a(4, 5), b(4.5, 4.5);
    std::cout << a.area() << ' ' << a.perimeter() << ' ' << a.is_square() << '\n';
    std::cout << b.area() << ' ' << b.perimeter() << ' ' << b.is_square() << '\n';
    std::cout << (b.bigger_than(a) ? "b" : "a") << " is bigger\n";
    try {
        Rectangle bad(-1, 2);
    } catch (const std::invalid_argument& e) {
        std::cout << "error: " << e.what() << '\n';
    }
    return 0;
}

Output Verified by compiling and running

20 18 0
20.25 18 1
b is bigger
error: sides must be positive

Validating in the constructor guarantees every Rectangle object is valid. Functions that only read the object are const.

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