When I don't declare a constructor for example, the compiler will provide me with a default constructor that will have no arguments and no definition (empty body), and thus, will take no action.
So, if I'm finished with an object for example, wouldn't the default destructor reallocate (free) memory used by the object? If it doesn't, why are we getting it?
And, maybe the same question applies to the default constructor. If it does nothing, why is it created for us by default?
The default destructor calls the destructors of the base class and members of the derived class. The destructors of base classes and members are called in the reverse order of the completion of their constructor: The destructor for a class object is called before destructors for members and bases are called.
If you dynamically allocate memory, and you want this memory to be deallocated only when the object itself is "terminated", then you need to have a destructor. The object can be "terminated" in two ways: If it was statically allocated, then it is "terminated" implicitly (by the compiler).
You only need to write your own destructor if you're managing a resource that isn't released automatically; for example, a raw pointer to something that you allocated with new . You shouldn't need such a thing in most classes - use containers, smart pointers and other RAII types to manage these automatically for you.
No. You never need to explicitly call a destructor (except with placement new ). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
It's wrong to say that a compiler-generated default constructor takes no action. It is equivalent to a user-defined constructor with an empty body and an empty initializer list, but that doesn't mean it takes no action. Here is what it does:
And only if a class is not polymorphic, has no base class and has no members that require construction, then a compiler-generated default constructor does nothing. But even then a default constructor is sometimes necessary for the reasons explained in other answers.
The same goes for the destructor - it calls base class'es destructor and destructors of all members which have them, so it isn't true in general case that a compiler-generated destructor does nothing.
But memory allocation really has nothing to do with this. The memory is allocated before the constructor is called, and it is freed only after the last destructor has finished.
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