Search code examples
c++oopleast-privilege

I have problem with least privilege principle. incrementing a member when an object is created


I want to keep track of the number of students in my system so, My idea was to make a static datamember in the "StudentController" class called "_numOfStudents" and increment it with the Student's constructor but it didn't work so, I moved it into the "Student" class and made that when a Student object is created the number increment by the help of the constructor. The problem is: isn't it not the Student class's business to know how many students are there thus breaking the principle of least privilege. what can I do better to keep track of the student objects' count.

    Student(string firstName, string lastName, int age,vector<float>&subjects)//Student conctructor
{
    SetFirstName(firstName);
    setLastName(lastName);
    SetAge(age);
    SetMarks(subjects);
    this->m_id++;
    StudentController::_numberOfStudents++;
}



    class StudentController//this is where i declared the static data member
{
private:
list<Student> _students;
public:
    static int _numberOfStudents;

    StudentController() {};
    StudentController(list<Student>& st) :_students(st) {};

        }
    }   
};

int StudentController::_numberOfStudents = 0;

Solution

  • When you try to do StudentController::_numberOfStudents++; in the constructor, the StudentController class is not yet defined, therefore the compiler doesn't know about that class and its static member.