Inheritance

Create a class called Rectangle so that, given a height and width, the object would calculate and display the length, width, the perimeter, and the area. Do not include a constructor for this class
Another class called Box is derived from the Rectangle class. This class given the breadth of the box, it should display the same pieces of information as the Rectangle. Additionally, the Box objectshould calculate and display its volume

Dani AI

Generated

For : this is best implemented in C++ (plain C has no classes or inheritance). The key constraints are: do not write a user-defined constructor for Rectangle (the compiler will supply a default one), and make sure the derived Box can use or query the rectangle dimensions. Two safe options are (a) keep width/height as protected so Box can reuse them, or (b) keep them private and provide protected/public getters/setters. Important: a default-constructed object’s built-in members may be uninitialized unless you initialize them, so provide setters or brace-initialize members.

Example (minimal C++):

#include <iostream>

class Rectangle {
protected:
    double width{};   // value-initialized to 0.0
    double height{};
public:
    // no user-defined constructor
    void setDimensions(double h, double w) { height = h; width = w; }
    double area() const { return width * height; }
    double perimeter() const { return 2 * (width + height); }
    void print() const {
        std::cout << "Width: " << width << " Height: " << height
                  << " Perimeter: " << perimeter() << " Area: " << area() << '\n';
    }
};

class Box : public Rectangle {
private:
    double breadth{};
public:
    void setBreadth(double b) { breadth = b; }
    double volume() const { return width * height * breadth; }
    void print() const {
        Rectangle::print();
        std::cout << "Breadth: " << breadth << " Volume: " << volume() << '\n';
    }
};

Notes and cautions: prefer double or another floating type if fractional dimensions are allowed. Validate inputs (non-negative) before computing. Reuse Rectangle methods from Box rather than duplicating area/perimeter logic. If the assignment really expects C, translate the idea to structs and functions, but for class-based inheritance use C++. As reminded, follow forum rules when posting homework requests; and ’s point about not doing paid homework is a relevant community caution.

Recommended Answers

All 2 Replies

Read the forum rules and adhere to them, or I'll continue to delete your threads.

How about I do your homework for you if you do my homework for me. Deal?

:rolleyes:

But actually, no, I'd rather not, because then I'd be wasting a lot of money spent on this education.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.