Student Counter

Student Counter

Create a Student class with private member variables name and id. Add a static member variable student_count to keep track of the number of Student instances. Increment student_count in the constructor and decrement it in the destructor. Print the student_count before and after creating multiple Student instances.

Hint

Remember to initalize static variables outisde of the class.

Answer

#include <iostream>
#include <string>

class Student {
public:
    std::string name;
    int id;
    static int student_count;

    // Constructor to initialize member variables and increment student_count
    Student(const std::string& student_name, int student_id) 
        : name(student_name), id(student_id) {
        ++student_count;
    }

    // Destructor to decrement student_count
    ~Student() {
        --student_count;
    }

    // Static function to get the current student_count
    static int get_student_count() {
        return student_count;
    }
};

// Initialize the static member variable
int Student::student_count = 0;

int main() {
    std::cout << "Initial student count: " << Student::get_student_count() << std::endl;

    {
        Student s1("Alice", 101);
        Student s2("Bob", 102);
        Student s3("Charlie", 103);

        std::cout << "Student count after creating instances: " << Student::get_student_count() << std::endl;
    } // s1, s2, and s3 go out of scope here

    std::cout << "Student count after destroying instances: " << Student::get_student_count() << std::endl;

    return 0;
}
Questions