Rectangle initalization
Define a Rectangle struct with float width and float height members. Include a default constructor and a parameterized constructor using member initializer lists. The default constructor should initialize width and height to 1 by using the other constructor. Create instances using both constructors and print the dimensions.
- 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 includes validation to ensure all dimensions are positive. Create instances of Box with valid and invalid dimensions and print appropriate messages.
Answer
#include <iostream>
struct Rectangle {
float width;
float height;
// Parameterized constructor with member initializer list
Rectangle(float w, float h) : width(w), height(h) {}
// Default constructor with member initializer list
Rectangle() : Rectangle(1.f, 1.f) {}
void display_dimensions() const {
std::cout << "Width: " << width << ", Height: " << height << std::endl;
}
};
int main() {
// Using default constructor
Rectangle rect1;
std::cout << "Rectangle 1 (default constructor):" << std::endl;
rect1.display_dimensions();
std::cout << std::endl;
// Using parameterized constructor
Rectangle rect2(5.5, 10.2);
std::cout << "Rectangle 2 (parameterized constructor):" << std::endl;
rect2.display_dimensions();
return 0;
}