Reputation: 63
In class Faculty, I have a set of Subjects. I want to go through this set and on each subject call a function that adds a student to this subject. Here is how my function looks.
void Faculty::addStudent(Student* n) {
this->Students.insert(n);
set<Subject*>::iterator it;
for(it = this->Subjects.begin(); it != this->Subjects.end(); it++) {
(*it)->addStudent(n);
}
}
The problem is that I get an error:
Unhandled exception at 0x01341c6d in University.exe: 0xC0000005: Access violation reading location 0x1000694d.
I am using Micorosft Visual 2010.
I am new to C++.
I can provide any other necessary information, just don't know which. Please tell me if something is needed.
class Student: public Human {
friend class University;
friend class Faculty;
friend class Subject;
public:
Student(string name, string surname);
~Student();
void Index(int n);
private:
int index;
};
Upvotes: 3
Views: 10552
Reputation: 232
In most cases, such this, better practice is using smart pointers instead of raw data pointers when data shared between two or more classes.
Example. At first, we wrap pointers like this:
typedef shared_ptr<Student> StudentSPtr;
typedef shared_ptr<Subject> SubjectSPtr;
After this, we replace raw pointers by these pointers (StudentSptr n
instead of Student* n
) in the entire code. So, your function may look like this:
void Faculty::addStudent(StudentSptr n){
this->Students.insert(n);
vector<SubjectSPtr>::iterator it; //in your case vector is more proper, I think
for(it = this->Subjects.begin(); it != this->Subjects.end(); it++){
(*it)->addStudent(n);
}
}
Upvotes: 10