3 ms·
#3 should really say "make polymorphic public base class destructors virtual." There are reasons why you might want to use public inheritance that have nothing
by Suncho 12y ago
#3 should really say "make polymorphic public base class destructors virtual."
There are reasons why you might want to use public inheritance that have nothing to do with run-time polymorphism.
- nly 12y agoRight, but unless your Base or Derived class is going to pass Base*/&s to friends and/or other instances, you typically don't want your protected destructors to be virtual just so you can get safe destruction. Of course, the thing with C++ is, the longer you sit and think about it, the more reasons you can come up with a reason to do something atypical Slicing isn't even necessarily harmful either... but I'm not sure what you had in mind.
- jfoutz 12y agoI haven't touched C++ in years. Why would you ever make a non-virtual destructor? Isn't it totally up to the user of a class if they choose to inherit from the class? It seems like, if you're not providing a virtual destructor, you force users into delegation rather than inheritance, and that will catch some % of developers who aren't on the ball. They'll have leaks... As far as i know (old info) there's no such thing as a "final" class, so anybody can inherit even if you don't want them to.
- gurkendoktor 12y agoInheriting from value types is a bag of hurt thanks to issues like slicing: http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c http://stackoverflow.com/questions/274626/what-is-the-slicin... Anyone can technically publicly inherit from a value class, but if they do it's absolutely their fault :)
- flebron 12y agoHaving any virtual member functions, unless the compiler can devirtualize it, will hurt both space usage (since you now need a per-object vtable) and cache performance (since destruction now has to go through an indirection every time, instead of being a globally visible function). You have the `final` specifier since C++11 to state a class cannot be inherited from, but this notion of "You really shouldn't inherit from this class." has been around since classical object orientation has, C++ just couldn't express it as a language. So if your class currently isn't being inherited from, make your public dtor nonvirtual. If and when it needs to be a base class, then the author can modify your class to have a virtual dtor, or use composition (which is often the superior alternative). If source code is not available, then composition it is. I would advise against making it virtual "just in case", that's premature pessimisation.