Create a class `Box` with constructor overloading to initialize dimensions and calculate volume of the box.

SOLUTION.....

Box Class in C++ — Demo Page
#include <iostream>
using namespace std;

class Box {
private:
    float length, breadth, height;

public:
    // Default constructor
    Box() {
        length = breadth = height = 0;
    }

    // Constructor with one parameter (cube)
    Box(float side) {
        length = breadth = height = side;
    }

    // Constructor with three parameters (rectangular box)
    Box(float l, float b, float h) {
        length = l;
        breadth = b;
        height = h;
    }

    // Function to calculate volume
    float volume() {
        return length * breadth * height;
    }

    // Function to display details
    void display() {
        cout << "Box Dimensions:\n";
        cout << "Length: " << length << endl;
        cout << "Breadth: " << breadth << endl;
        cout << "Height: " << height << endl;
        cout << "Volume: " << volume() << endl;
    }
};

int main() {
    Box b1;            // Default constructor
    Box b2(5);         // Cube with side 5
    Box b3(4, 6, 8);   // Rectangular box

    cout << "Default Box:\n";
    b1.display();

    cout << "\nCube Box:\n";
    b2.display();

    cout << "\nRectangular Box:\n";
    b3.display();

    return 0;
}

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *