0
votes

I have a little problem and can't find a way to fix it..

In my .hpp file I have declared these two functions and struct but getting the error 'passing ‘const std::__cxx11::list<>’ as ‘this’ argument discards qualifiers.'

struct Student {
    std::string name;
    std::string student_id;

};

class StudentRegistry {

public:
    StudentRegistry(){}
    void Add(const Student &t);
    const std::list<Student>& GetStudents() const;

private:
    std::list<Student> students;
};

And in .cpp file I have tried to do:

void StudentRegistry::Add(const Student &t){
    this->GetStudents().push_back(t);
}

const std::list<Student>& StudentRegistry::GetStudents() const{
    return students;
}

How can I make this work?

1

1 Answers

2
votes
const std::list<Student>& GetStudents() const;

and

this->GetStudents().push_back(t);

are in conflict. You have a contract to not modify the list you get from GetStudents(), but you try to do that with push_back.

Solution:

void StudentRegistry::Add(const Student& t) {
    students.push_back(t);
}