I have a method involving copying some custom types from one linked list to another, based on very simple criteria. This is to be done using an assignment operator. At the end of the method, this new list is displayed, then deleted. The issue here, is that deleting the new list also deletes the original list's corresponding nodes, which signals to me that either the assignment operator is not functioning as intended, or the method in question has issues.
The method itself appears to work fine. It successfully navigates the copy of the original list, identifies Students who meet the desired criteria, and adds them to the newList
. It then goes on to display the expected contents of newList
just fine, and exits the method without error. The issue, then, is that the corresponding nodes in the original list are deleted too, not just those in newList
. This can be verified by the fact that displaying the list crashes when reaching one of the selected nodes, or by exiting the program before it crashes -- this saves the original list to a text file, which when opened, shows that the entries have been replaced with incorrect values.
The method in question:
void moreThan80Credits()
{
Container* tempList = list;
Container* newList = new Container();
Container* studentToAdd = new Container();
Container* head = new Container();
while(tempList) {
if(tempList->student->getCredits() > 80) {
studentToAdd->student = tempList->student;
if(!newList->student) {
newList->student = studentToAdd->student;
head = newList;
} else {
while(newList->next) {
newList = newList->next;
}
newList->next = studentToAdd; // adding to tail
}
}
tempList = tempList->next;
}
newList = head; // returning to beginning of newList, to display.
if(!newList->student) {
cout << endl << "There are no students with more than 80 credits." << endl;
return;
}
cout << "The students with more than 80 credits are:" << endl;
while(newList) {
newList->student->displayInfo();
Container* removal = newList;
newList = newList->next;
delete removal->student; // displaying and deleting, together
delete removal;
}
return;
}
And then the assignment operator:
Student& Student::operator=(const Student& s) {
if (this == &s) return *this; // self assignment check
this->name = s.name;
this->rollNo = s.rollNo;
this->level = s.level;
this->credits = s.credits;
return *this;
}
And the relevant constructors:
Student::Student() { // default constructor
// empty, everything should be null
}
Student::Student(const Student& that) { // copy constructor
this->name = that.name;
this->rollNo = that.rollNo;
this->level = that.level;
this->credits = that.credits;
}
As stated before, the deletion section at the end of moreThan80Credits()
deletes both copies of the node. I am wondering why this is, and how the code provided can be modified to make this behavior cease. Thank you all.