#include <iostream>
#include <string>

// Define a Student class
class Student {
private:
    // Private member variables (data hiding)
    std::string name;
    int age;
    float score;

public:
    // Constructor: automatically called when creating objects, used to initialize member variables
    Student(const std::string& n, int a, float s) {
        name = n;
        age = a;
        score = s;
        std::cout << "Constructor called, student " << name << " has been created." << std::endl;
    }

    // Destructor: automatically called when objects are destroyed, used to clean up resources (for demonstration only)
    ~Student() {
        std::cout << "Destructor called, student " << name << " is about to be destroyed." << std::endl;
    }

    // Public member functions: set student information
    void setName(const std::string& n) {
        name = n;
    }

    void setAge(int a) {
        if (a > 0) age = a;  // Simple validity check
    }

    void setScore(float s) {
        if (s >= 0 && s <= 100) score = s;
    }

    // Public member functions: get student information
    std::string getName() const {
        return name;
    }

    int getAge() const {
        return age;
    }

    float getScore() const {
        return score;
    }

    // Display all student information
    void display() const {
        std::cout << "Name: " << name << ", Age: " << age << ", Score: " << score << std::endl;
    }

    // Check if passed (member function example)
    bool isPassed() const {
        return score >= 60;
    }
};

int main() {
    // Create object using constructor (stack object)
    Student stu1("Zhang San", 20, 85.5);
    stu1.display();

    // Create another object
    Student stu2("Li Si", 19, 58.0);
    stu2.display();

    // Call member function to check if passed
    if (stu2.isPassed()) {
        std::cout << stu2.getName() << " passed." << std::endl;
    } else {
        std::cout << stu2.getName() << " failed." << std::endl;
    }

    // Modify stu2's information
    stu2.setScore(75.5);
    stu2.setName("Li Si (after retake)");
    std::cout << "After modification ";
    stu2.display();

    // Dynamically create object (heap object), need to manually delete
    Student* stu3 = new Student("Wang Wu", 22, 90.0);
    stu3->display();
    delete stu3;   // Call destructor and release memory

    // Objects stu1 and stu2 will automatically call destructors when leaving scope
    return 0;
}

results matching ""

    No results matching ""