I am learning memory management in C++ and I don\'t get the why only some of the destructors are called when leaving scope. In the code below, only obj1 destructor is called
obj2 -> ~cl1 ;
Don't do this! Use delete obj2;
instead.
Addendum
What you were trying to do was to call the destructor explicitly. Your code does not do that. Your code is getting the address of the destructor and then dropping it into the bit bucket. Your code is a no-op. The correct way to explicitly call the destructor is obj2->~cli();
.
Explicitly calling the destructor is usually something you should not do.
What you should do is to delete the memory created by new
. The correct way to do that is to use the delete
operator. This automatically calls the destructor and releases the memory. The destructor does not release the memory. Failing to use delete results in a memory leak.