5. Class with Allocated Memory

z6.5-destructor.cc
class MyClass { public: MyClass(); ~MyClass(); private: int* subObj; };

MyClass::MyClass() {
   subObj = new int; // Allocate mem for data
   *subObj = 0;
}

MyClass::~MyClass() {
   delete subObj; // without this, subObj would never be deallocated
}
Each new must have a corresponding delete, otherwise there is a memory leak.

To prevent memory leaks, and crashes, a class using new should have:

  • destructor

  • copy constructor

  • copy assignment operator