So I did this sorted doubly linked list code. I am supposed to overload a couple of operators. However, when I try to create a new SDL (sorted doubly list) inside one of the functions, it will destroy itself before I manage to return it to the main function. I tried to debug this so many times. I see where the error occurs but I have no clue how to solve it. Here is the code where things mess up.
SortedDoublyLinkedList SortedDoublyLinkedList::operator+(const SortedDoublyLinkedList & otherList)
{
SortedDoublyLinkedList myNewList(otherList);
Node *currentNode = head;
while (currentNode) {
myNewList.add(currentNode->value);
currentNode = currentNode->next;
}
return myNewList; // destroys itself
}
Above function will overload when in the main the coder writes "mylist = mylist + mylist2" to add 2 lists together.
Here is another:
SortedDoublyLinkedList SortedDoublyLinkedList::operator+(const int & myNumber)
{
SortedDoublyLinkedList myNewList(*this);
myNewList.add(myNumber);
return myNewList; // destroys itself
}
Same deal.
Test cases are these below:
myList += myList2; // works properly!
myList += myList + 15; // works properly!
SortedDoublyLinkedList myList3 = myList + 15; // creates a new list without modifying myList, works properly!
Error occurs when the user types in:
myList = myList + myList2;
myList = myList + 15;
I got no clue why this is happening. Inside the above 2 functions, myNewList will destroy itself before returning, then at the very end of the program, it will try to destroy itself one more time (what?) but since it's already deallocated it will fail destroying it and then an error pops up.