Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my destructor never called?

I have a base class A and a derived class B:

class A
{
public:
    virtual f();
};

class B : public A
{
public:
     B()
     {
         p = new char [100];
     }
     ~B()
     {
         delete [] p;
     }
     f();
private:
    char *p;
};

For any reason the destructor is never called - why? I dont understand this.

like image 506
Herb Slotinsky Avatar asked Aug 22 '09 08:08

Herb Slotinsky


2 Answers

Your base class needs a virtual destructor. Otherwise the destructor of the derived class will not be called, if only a pointer of type A* is used.

Add

virtual ~A() {};

to class A.

like image 177
Manfred Meyer Avatar answered Sep 28 '22 03:09

Manfred Meyer


Class A should have a virtual destructor. Without that, derive class destructors won't be called.

like image 30
Andrew Avatar answered Sep 28 '22 03:09

Andrew