Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 230
Shea Levy Avatar asked Nov 18 '25 22:11

Shea Levy


2 Answers

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.

like image 180
John Dibling Avatar answered Nov 20 '25 10:11

John Dibling


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().

like image 44
Oberon Avatar answered Nov 20 '25 10:11

Oberon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!