Person Invariants
Define a Person class with private member variables name, age, and h2eight. Add a public constructor to initialize these variables and public methods to get and set their values. Ensure age and height are positive. Create instances of Person and demonstrate the use of its methods.
Answer
#include <iostream>
#include <string>
class Person {
private:
std::string name;
int age;
float height;
public:
// Constructor to initialize member variables
Person(const std::string& person_name, int person_age, float person_height)
: name(person_name), age(person_age), height(person_height) {
if (age < 0) age = 0; // Ensure age is positive
if (height < 0) height = 0; // Ensure height is positive
}
// Getter for name
std::string get_name() const {
return name;
}
// Setter for name
void set_name(const std::string& person_name) {
name = person_name;
}
// Getter for age
int get_age() const {
return age;
}
// Setter for age with validation
void set_age(int person_age) {
if (person_age >= 0) {
age = person_age;
} else {
std::cout << "Age must be positive." << std::endl;
}
}
// Getter for height
float get_height() const {
return height;
}
// Setter for height with validation
void set_height(float person_height) {
if (person_height >= 0) {
height = person_height;
} else {
std::cout << "Height must be positive." << std::endl;
}
}
// Print person details
void print_details() const {
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Height: " << height << " cm" << std::endl;
}
};
// `main` is here for demonstration purposes only
int main() {
// Create instances of Person
Person person1("Alice", 30, 165.5);
Person person2("Bob", -5, 180.0); // Invalid age
Person person3("Charlie", 25, -170.0); // Invalid height
// Print initial details
std::cout << "Person 1 details:" << std::endl;
person1.print_details();
std::cout << std::endl;
std::cout << "Person 2 details:" << std::endl;
person2.print_details();
std::cout << std::endl;
std::cout << "Person 3 details:" << std::endl;
person3.print_details();
std::cout << std::endl;
// Set new values
person1.set_name("Alicia");
person1.set_age(35);
person1.set_height(167.0);
// Attempt to set invalid values
person2.set_age(-10);
person3.set_height(-175.0);
// Print updated details
std::cout << "Updated Person 1 details:" << std::endl;
person1.print_details();
std::cout << std::endl;
std::cout << "Updated Person 2 details (after attempting to set invalid age):" << std::endl;
person2.print_details();
std::cout << std::endl;
std::cout << "Updated Person 3 details (after attempting to set invalid height):" << std::endl;
person3.print_details();
return 0;
}