简体   繁体   中英

Should classes be final by default?

Quoting the Effective C++ (Scott Meyers), third edition, item 7:

Declare destructors virtual in polymorphic base classes.

This implies that classes intended to be inherited from should, at a minimum, have the destructor virtual.

When writing some applications/libraries, some classes (I would say not few) are not designed with the intention of being inherited from. We usually rely on some conventions, in which one is not supposed to inherit classes that are not his own or without checking if it's safe to.

Now, a coding standard may require to write and design classes such that inheritance is always safe. I feel like this might be too much. C++11 has added the final keyword that makes sure classes are not inherited from. Would you recommend marking all classes that are not designed for inheritance as final by default?

This would make the compiler enforce what we have been doing by convention for ages. But that convention might be considered well enough understood and easy to follow (especially since inheritance is usually avoided, with composition being preferred) such that it might be just another thing to care of while writing the code.

Just because a class does not have any virtual functions does not mean that inheriting from it does not make sense. It just means it was probably not intended and that you have to be careful not to delete any instances of the derived objects through pointers to the base class. private inheritance would often be used in such a case, as an alternative to composition, to signal that inheriting from the base is purely an implementation detail and the derived class is not to be considered as having a "is-a" relationship with the base.

Marking a class final is a great way to express that a class is not intended to be derived from, at all, by making it impossible. So if that's what you want, slap a final on the class.

In some cases, marking a (derived) class final to prevent any further derivatives can also have the added benefit of making it easier for the compiler to devirtualize function calls, thus leading to better performance in some cases.

In my opinion, final should (usually) be the default and you can then remove it later if you find that you need/want to derive from the class after all. But that's just opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM