The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can't manage to achieve that.
I have this:
class N { public: ~N() { std::cout << "Destroying object of type N"; } }; class M { public: M() { n = new N; } // ~M() { //this should happen by default // delete n; // } private: N* n; };
Then this should print the given message, but it doesn't:
M* m = new M(); delete m; //this should invoke the default destructor
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
Default destructors call destructors of member objects, but do NOT delete pointers to objects.
Destructor is also a special member function like constructor. Destructor destroys the class objects created by constructor.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
What makes you think the object n
points to should be deleted by default? The default destructor destroys the pointer, not what it's pointing to.
Edit: I'll see if I can make this a little more clear.
If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed?
{ Thing* t = new Thing; // do some stuff here // no "delete t;" }
The t
pointer is cleaned up, but the Thing
it points to is not. This is a leak. Essentially the same thing is happening in your class.
Imagine something like this:
class M { public: M() { } // ~M() { // If this happens by default // delete n; // then this will delete an arbitrary pointer! // } private: N* n; };
You're on your own with pointers in C++. No one will automatically delete them for you.
The default destructor will indeed destroy all member objects. But the member object in this case is a pointer itself, not the thing it points to. This might have confused you.
However, if instead of a simple built-in pointer, you will use a smart pointer, the destruction of such a "pointer" (which is actually a class) might trigger the destruction of the object pointed to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With