Why do C++ objects have a default destructor?

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:

  1. It calls the base class’es default constructor.
  2. It initializes the vtable pointer, if the class is polymorphic.
  3. It calls the default constructors of all members that have them. If there is a member with some constructors, but without a default one, then it’s a compile-time error.

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.

Leave a Comment

tech