Search code examples
c++linked-listdestructor

Is Destructor is mandatory in linked lists?


I made a singly linked list program.

I want to know is there any need of destructor or default destructor will work fine ?

class sll
{
    node*head;
    node*tail;
public:
    sll()
    {
        head=tail=0;
    }
    sll(const sll & obj1);
    void addtohead (int x);
    void addtotail (int x);
    int deletefromhead();
    int deletefromtail();
}

Solution

  • default destructor will only deallocate the memory of head and tail because sll() constructor only initialize head and tail to 0 at time of object intilization

    it will not work for dynamically allocated nodes.Implement the following code in your class.

    ~sll()
    {
        node *p = head;
        while (head !=NULL)
        {
            head= head -> next;
            delete p;
            p=head;
        }
    }