Do I need a virtual destructor if descendant classes have no non-static members or destructors? [duplicate]

StackOverflow https://stackoverflow.com/questions/21937739

  •  14-10-2022
  •  | 
  •  

سؤال

I'm playing around with a class hierarchy for file descriptors, where the base class holds an int and calls close on it during destruction and child classes don't add any virtual methods or data members, just differ in their construction (e.g. the named_file_filedes takes a path and initializes the base with open in the ctor) or non-virtual member functions (e.g. you can only call kevent on a kqueue_filedes). Given this, does the base class need a virtual destructor? The size of the child classes is all the same and none of them have custom destruction logic. Tagged c++11 as that's the standard version I'm targeting.

هل كانت مفيدة؟

المحلول 2

If you delete derived classes via pointers to base classes then the behavior will be undefined without a virtual destructor, no matter how the derived classes look.

C++11 Standard, §5.3.5/3:

If the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

However, if the classes differ only in their constructor, consider using alternatives to derivation, e.g. simple free functions like create_named_file().

نصائح أخرى

You'll need a virtual destructor if you intend to destroy a derived class object by deleteing a base class pointer. Such as:

class Foo {};
class Bar : public Foo {}

int main()
{
  Foo* f = new Bar;
  delete f; // << UNDEFINED BEHAVIOR without virtual destructor in base classe
}

You'll also need at least 1 virtual method in the base if you require the object to be polymorphic -- for instance, if you intend to use dynamic_cast to go from base to derived. Commonly a virtual destructor is provided in this case. Having only a virtual destructor is sufficient to ensure the class is polymorphic.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top