0

Example:

class A
{
   char * data;
   ...
   A(){data = new char[50];}
   ~A(){delete [] data;}
};

class B
{
   A a;

   B();
   // default destructor
}

void foo()
{
   B b;
}

int main()
{
   foo();

   // "A.data" still in the heap or no?
}

This program is correct and "A.data" will be removed after foo() in main, or will be still exist in the heap?

3 Answers3

5

Yes it will be removed, thru you need to use delete[] for arrays. Also you should keep in mind Rule of three

Community
  • 1
  • 1
alexrider
  • 4,449
  • 1
  • 17
  • 27
3
~A(){delete data;}

should be

~A()
{
    delete[] data;
 }
 //remove the dynamic array

In your current code, when main exits, it will call the destructor to release memory and will not exist in heap.

taocp
  • 23,276
  • 10
  • 49
  • 62
2

When an object is destructed, the compiler automatically destructs all of the class's non-pointer data members. So when your B b variable goes out of scope, the compiler automatically destructs it, which in turn destructs the A a data member since it is not a pointer, which calls ~A() to free the array.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770