I'm having some trouble trying to return an instance from a list of instances from a function.
I have a set where I store instances of my Student class. I'm trying to return an instance from the "find" function to be able to find this instance based on the student name, I am calling this function in another class/file. I want to be able to get this object instance in another file, edit certain properties and have it update in that list of instances.
My find function in Student.cpp:
static set<Student, StudentCmp> studentInstances;
Student* Student::find(int studentId) {
Student *foundStudent = new Student();
for (Student s: studentInstances) {
if(s.getStudentID() == studentId) {
foundStudent = &s;
}
}
return foundStudent;
}
In another class:
*Student::find(1).setStudentName("John");
Yes this student ID does exist in the list, and inside the find function everything is working fine. It finds the ID and the relevant address, however when I try to point to this variable using the address given to me by my find function I get this error:
Unhandled exception at 0x7622DFD8 in Driver.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x006EF044
I'm assuming that the address is going out of bounds? I don't know why but it looks like the address no longer points to my object when it goes out of the function, I looked this up to find answers and people said to use the "new" keyword to keep the object on the heap but this doesn't seem to work for me.
Any advice to achieve what I want to do?
for (Student& s :...)
, and now&s
will take the address of the Student object in the set.find
is definitely not needed. See: en.cppreference.com/w/cpp/container/set/find