I have a C++ class, MyClass. It contains a constructor, destructor and an int pointer private: int *MyPtr;.
Somewhere, I allocate dynamically a MyClass Object:
MyClass *my = new MyClass(); //...
Then I call delete my;
Should MyClass have a destructor which uses something like delete MyPtr? Or is that MyPtr destroyed when I call delete my?
Or is that MyPtr destroyed when I call delete my?No, when you call
delete my;this will call the destructor ofMyClassand unless you explicitly delete MyPtr in the destructor you will have a memory leak.Should MyClass have a destructor which uses something like delete MyPtr?Always delete dynamically allocated memory in your destructor – that is what destructors are meant for.