0

I understand that we should use virtual destructors in base classes to ensure proper resource disposal, because it guarantees the inheritance chain will be observed and all parent destructors will be called when destructing an object. That being said, do we also need virtual destructors in base classes when both the base class and any subclasses use only the default destructor? Example:

class Printable {
  virtual std::string print();
};

class A : public Printable {
  int foo;
  bool bar;
  std::string print() override;
}

class B : public Printable {
  std::vector<int> foo;
  std::string print() override;
}

There are no resources being managed, and all destructors are implicitly default. Is it still advisable to specify a virtual destructor in Printable?

Jackson
  • 559
  • 7
  • 20
  • 3
    A default destructor is not the same a destructor that does nothing. The destructor still needs to be called even if it's the compiler generated one (default one). – François Andrieux Apr 18 '18 at 14:54
  • So yes, there should be a `virtual ~Printable() {}` definition? – Jackson Apr 18 '18 at 14:56
  • 4
    The base type still needs a `virtual` destructor, though you can still use the default destructor by using `virtual ~Printable() = default;`. – François Andrieux Apr 18 '18 at 15:00
  • Thank you. Would all subclasses need to also explicitly define a destructor? – Jackson Apr 18 '18 at 15:18
  • 1
    You need a virtual destructor if your code deletes an object of a derived type through a pointer to the base. If the destructor in that situation is not virtual the behavior is **undefined**. That **might** show up as failing to free resources, but there is no such requirement; the language definition does not tell you what that program will do. – Pete Becker Apr 18 '18 at 15:19
  • 1
    The use of default destructor vs user-defined destructor has no relation at all on how `virtual` and destructors interact. Types inherited from in a polymorphic context need a `virtual` destructor if destruction through a pointer to base type is possible, regardless of whether or not any of the classes involve has explicit destructor implementations or use the default destructor. – François Andrieux Apr 18 '18 at 15:20

0 Answers0