My C++ is a little rusty but I have made a program that reverses a linked list and now I am trying to write the proper destructors for it but I don’t know exactly what to destroy. Here are my class definitions:
class LinkedList
{
private:ListElement *start;
public:LinkedList();
public:void AddElement(int val);
public:void PrintList();
public:void InvertList();
};
class ListElement
{
public:int value;
public:ListElement * link;
public:ListElement(int val);
public:ListElement();
};
class Stack
{
private:ListElement ** stack;
private:int index;
public:Stack(int size);
public:void push(ListElement * le);
public:ListElement * pop();
};
The stack is for when I reverse the list.
Anyway …
How would I go about writing the destructors for these?
I was thinking:
For the ListElement make the value 0 and the link 0(NULL).
For the LinkedList go through the elements and call up the ListElementDestructor for all of them.
I am not very sure about this because as I understand the destructor automatically calls the destructors of the member objects so would only writing an empty destructor for LinkedList suffice in this case? I don’t know … that is why I am asking
For the stack I don’t know … the pointers are already 0(NULL) after the list is inversed because they are all poped.
I am a bit confused.
Can anyone help?
Thank you in advance.
You don’t need to reset any of the values in the destructor, as values won’t exist after the destructor executed.
The main thing you need to be sure of is that all elements allocated on the heap (i.e Using
new) are deleted usingdelete(ordelete []in the case of arrays).For a object allocated on the stack it is automatically called when the object goes out of scope.
For a dynamically allocated object (i.e created using
new) the destructor is called whenit is deleted using
delete. In other words, you don’t need to call any destructors as they are called automatically if you clean up your objects correctly.Given (I assume) that you are allocating new ListElements on the heap in the LinkedList class, you should ensure that in the LinkedList destructor, every ListElement is deleted in the destructor by walking down the list and calling delete on every ListElement (after you have retrieved the address of the next list element from it of course). Something like this:
There is nothing in the ListElement class that needs cleaning up, as although it has a pointer to the next element the deletion should probably be handled in the LinkedList class, which means it doesn’t need a destructor.
It isn’t required that you write a destructor for every class, as the compiler will automatically generate an empty one for you.
As I said in the comments, you shouldn’t be using a stack for reversing a linked list. You should just be swapping the direction of the pointers.
An quick example of roughly the sort of thing you would want.