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 (body), and thus, will take no action.
If I now don't declare a destructor
, the compiler will provide me with a default destructor
with no defintion (body), and thus, I think 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 doesn nothing, why is it created for us by default?
Thanks.
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.