I tried adding a destructor to my class with "delete next;" and "delete previous;" but the program had a run time error. |
Consider this. Suppose you have a train with two cars, 1 and 2. Car 1's previous is nullptr and its next is car 2, while car 2's previous is car 1 and its next is nullptr.
Suppose your destructor looks like this:
1 2 3 4
|
train::~train(){
delete this->previous;
delete this->next;
}
|
Finally, suppose that you start by deleting car 1.
Then the order of operations will be this:
delete car1->previous; // car1->previous == nullptr, so this does nothing
delete car1->next; // car1->next == car2, so move into car2's destructor
delete car2->previous; // car2->previous == car1, so move into car1's destructor
delete car1->previous; // car1->previous == nullptr, so this does nothing
delete car1->next; // car1->next == car2, so move into car2's destructor
delete car2->previous; // car2->previous == car1, so move into car1's destructor
And so on, until the stack runs out.
Can you figure out how to fix this?