CS246 Lecture Notes - Lecture 25: Function Pointer, Virtual Function, Stack-Based Memory Allocation
Document Summary
After learning about inheritance, we must look at how it"s changed things . Consider the following example class x { int *x; public: Y(int m, int n): x{n}, y{new int [m]} { } ~y() {delete [] y;} // the last thing y"s destructor does is call x"s destructor class y: public x { X *myx = new y{10, 20}; delete myx; If you run this through valgrind, you will notice there is a memory leak! You are deleting a pointer to x, so x"s dtor runs. So only x, but not y, is freed. Always do this in classes that are meant to have subclasses!! This applied even if the dtor would have an empty body and not do anything. Because you don"t know what deallocation might be needed in the subclasses. class x { public: virtual ~x() {delete [] x;} If a class is not meant to have subclasses, declare it final.