[c++] Does delete on a pointer to a subclass call the base class destructor?

I have an class A which uses a heap memory allocation for one of its fields. Class A is instantiated and stored as a pointer field in another class (class B.

When I'm done with an object of class B, I call delete, which I assume calls the destructor... But does this call the destructor of class A as well?

Edit:

From the answers, I take that (please edit if incorrect):

  1. delete of an instance of B calls B::~B();
  2. which calls A::~A();
  3. A::~A should explicitly delete all heap-allocated member variables of the A object;
  4. Finally the memory block storing said instance of class B is returned to the heap - when new was used, it first allocated a block of memory on heap, then invoked constructors to initialize it, now after all destructors have been invoked to finalize the object the block where the object resided is returned to the heap.

The answer is


I was wondering why my class' destructor was not called. The reason was that I had forgot to include definition of that class (#include "class.h"). I only had a declaration like "class A;" and the compiler was happy with it and let me call "delete".


It is named "destructor", not "deconstructor".

Inside the destructor of each class, you have to delete all other member variables that have been allocated with new.

edit: To clarify:

Say you have

struct A {}

class B {
    A *a;
public:
    B () : a (new A) {}
    ~B() { delete a; }
};

class C {
    A *a;
public:
    C () : a (new A) {}        
};

int main () {
    delete new B;
    delete new C;
}

Allocating an instance of B and then deleting is clean, because what B allocates internally will also be deleted in the destructor.

But instances of class C will leak memory, because it allocates an instance of A which it does not release (in this case C does not even have a destructor).


The destructor for the object of class A will only be called if delete is called for that object. Make sure to delete that pointer in the destructor of class B.

For a little more information on what happens when delete is called on an object, see: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.9


You should delete A yourself in the destructor of B.


If you have a usual pointer (A*) then the destructor will not be called (and memory for A instance will not be freed either) unless you do delete explicitly in B's destructor. If you want automatic destruction look at smart pointers like auto_ptr.


No. the pointer will be deleted. You should call the delete on A explicit in the destructor of B.


class B
{
public:
    B()
    {
       p = new int[1024];  
    }
    virtual ~B()
    {
        cout<<"B destructor"<<endl;
        //p will not be deleted EVER unless you do it manually.
    }
    int *p;
};


class D : public B
{
public:
    virtual ~D()
    {
        cout<<"D destructor"<<endl;
    }
};

When you do:

B *pD = new D();
delete pD;

The destructor will be called only if your base class has the virtual keyword.

Then if you did not have a virtual destructor only ~B() would be called. But since you have a virtual destructor, first ~D() will be called, then ~B().

No members of B or D allocated on the heap will be deallocated unless you explicitly delete them. And deleting them will call their destructor as well.


When you call delete on a pointer allocated by new, the destructor of the object pointed to will be called.

A * p = new A;

delete p;    // A:~A() called for you on obkect pointed to by p

no it will not call destructor for class A, you should call it explicitly (like PoweRoy told), delete line 'delete ptr;' in example to compare ...

  #include <iostream>

  class A
  {
     public:
        A(){};
        ~A();
  };

  A::~A()
  {
     std::cout << "Destructor of A" << std::endl;
  }

  class B
  {
     public:
        B(){ptr = new A();};
        ~B();
     private:
        A* ptr;
  };

  B::~B()
  {
     delete ptr;
     std::cout << "Destructor of B" << std::endl;
  }

  int main()
  {
     B* b = new B();
     delete b;
     return 0;
  }

You have something like

class B
{
   A * a;
}
B * b = new B;
b->a = new A;

If you then call delete b;, nothing happens to a, and you have a memory leak. Trying to remember to delete b->a; is not a good solution, but there are a couple of others.

B::~B() {delete a;}

This is a destructor for B that will delete a. (If a is 0, that delete does nothing. If a is not 0 but doesn't point to memory from new, you get heap corruption.)

auto_ptr<A> a;
...
b->a.reset(new A);

This way you don't have a as a pointer, but rather an auto_ptr<> (shared_ptr<> will do as well, or other smart pointers), and it is automatically deleted when b is.

Either of these ways works well, and I've used both.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to memory-management

When to create variables (memory management) How to check if pytorch is using the GPU? How to delete multiple pandas (python) dataframes from memory to save RAM? Is there a way to delete created variables, functions, etc from the memory of the interpreter? C++ error : terminate called after throwing an instance of 'std::bad_alloc' How to delete object? Android Studio - How to increase Allocated Heap Size Implementing IDisposable correctly Calculating Page Table Size Pointer-to-pointer dynamic two-dimensional array

Examples related to destructor

Is calling destructor manually always a sign of bad design? When is a C++ destructor called? How to destroy an object? How to force deletion of a python object? Creating an object: with or without `new` When should I create a destructor? How do I correctly clean up a Python object? Does delete on a pointer to a subclass call the base class destructor? Do I need to explicitly call the base virtual destructor? Dynamically allocating an array of objects

Examples related to delete-operator

Double free or corruption after queue::push Deleting a pointer in C++ C++ delete vector, objects, free memory Meaning of = delete after function declaration Is it safe to delete a NULL pointer? Is "delete this" allowed in C++? C++ Array of pointers: delete or delete []? delete vs delete[] operators in C++ How does delete[] know it's an array? Does delete on a pointer to a subclass call the base class destructor?

Examples related to base-class

Creating a singleton in Python Is it possible to assign a base class object to a derived class reference with an explicit typecast? Does delete on a pointer to a subclass call the base class destructor? Interface vs Base class