Box struct

Box

Create a Box struct with member variables for length, width, and height. Add a constructor that uses a member initializer list to initialize these variables and set the members to 1 if the constructor parameter is smaller than 0. Include a validation that tells the user if any of the dimention parameters were negative. Create instances of Box with valid and invalid dimensions and print appropriate messages.

Hint

Use the ternary operator in the member initalization list.

Answer

- Create a 2dPoint struct with member variables x and y. Overload the + operator to add two Point objects by summing their x and y values. Create instances of Point, add them using the + operator, and print the result. (also add - operator). Add a single float value constructor to add support for subtracting single floats. Also add * and / operators that take a float value.
#include <iostream>

struct Box {
    float length;
    float width;
    float height;

    // Constructor with member initializer list and validation
    Box(float l, float w, float h) : length(l > 0 ? l : 1), width(w > 0 ? w : 1), height(h > 0 ? h : 1) {
        if (l <= 0 || w <= 0 || h <= 0) {
            std::cout << "Warning: All dimensions must be positive. "
                      << "Non-positive dimensions set to 1." << std::endl;
        }
    }

    void display_dimensions() const {
        std::cout << "Length: " << length << ", Width: " << width << ", Height: " << height << std::endl;
    }
};

int main() {
    // Creating a Box with valid dimensions
    Box validBox(3.5, 4.2, 5.0);
    std::cout << "Valid Box:" << std::endl;
    validBox.display_dimensions();
    std::cout << std::endl;

    // Creating a Box with an invalid dimension
    Box invalidBox(-2.0, 3.0, 4.0);
    std::cout << "Invalid Box (with one negative dimension):" << std::endl;
    invalidBox.display_dimensions();
    std::cout << std::endl;

    // Creating a Box with all invalid dimensions
    Box allInvalidBox(-1.0, -1.0, -1.0);
    std::cout << "Invalid Box (with all negative dimensions):" << std::endl;
    allInvalidBox.display_dimensions();

    return 0;
}
Questions