Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I 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.



Having 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.


> per-object vtable

You mean per-object vtable pointer? Or per-type vtable?


Per object vtable pointer, yes.


Inheriting from value types is a bag of hurt thanks to issues like slicing: 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 :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: