LBaelish
LBaelish

Reputation: 689

Virtual Destructors and delete keyword

I've read a few other similar questions on the subject but I'm still confused on the use of delete for dynamically allocated memory and virtual destructors. If I have an object of class Base or of class Derived in a linked structure such that if I delete a node I also want to delete all nodes that can call this node an ancestor. Do I need to specify this in the destructor as shown below? Or will the use of a virtual destructor without the two deletes take care of this already?

class Base{ /*...*/ };

class Derived: public Base
{
    public:
       //various virtual functions//
       virtual ~Derived()
       {
           delete leftPtr;
           delete rightPtr;
       }
    private:
       Base* leftPtr = new Derived();
       Base* rightPtr = new Derived();
};

Upvotes: 0

Views: 2980

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Or will the use of a virtual destructor without the two deletes take care of this already?

Having a virtual destructor does not take care of deleting leftPtr and righPtr. A virtual destructor makes sure that the destructor corresponding to most derived object is called even when using delete on a base class pointer.

You haven't shown that Base has a virtual destructor. Assuming it does,

Derived* ptr1 = new Derived;
delete ptr1; // Calls ~Derived()

Base* ptr2 = new Derived;
delete ptr2; // Also calls ~Derived()

However, if you left out

delete leftPtr;
delete rightPtr;

from Derived::~Derived(), your code will leak memory.

Upvotes: 2

Related Questions