I think you may be confused about levels of indirection here. When an instance is destroyed, each data member does indeed get destroyed along with it. In your case, when an M
is destroyed and M::~M()
is called, its variable n
really is destroyed. The problem is that n
is a N *
, so while the pointer is destroyed, the thing it points to is not.
delete
does not work like this. Consider your simple statement:
delete n;
The above statement destroys the thing that n
points to, which is an object of type N
. It does not destroy n
itself, which is an N *
pointer.
There is a very good reason that M::~M()
does not automatically call delete n;
which is this: the N
object referred to might be shared between several M
objects, and if one M
were destroyed, the rest would lose the N
they were pointing at, leaving horrible dangling pointers everywhere. C++ does not attempt to interpret what you meant to do with your pointers, it just does what you told it to do.
In short, M
really is destroying all of its members when it is destroyed, it's just that this destruction doesn't do what you think it should do. If you want a pointer type which takes ownership of an object and destroys it when the pointer is destroyed, look at std::auto_ptr
.