Why is string class not final ?

Hi,

I have never come across a scenario where we derive from string class but still the string class is not a final class.

I have following points to ask :

1) Is string class really not intended to be a base class, if yes, why ?
2) If it is never intended to be a base class then why it is not marked as final ?
3) If it can be used as base class, then why the destructor of string class is not virtual.

Thanks alot for any help :)
1) Almost none STL containers are meant to be polymorphic base classes (there are a few exceptions for things like custom culture overrides and such). I don't know "why" exactly, but in general the philosophy behind C++ containers favors composition, not inheritance. Inheritance can be a mess, and the standard library creators probably wanted to avoid it for such re-usable objects, like std::string and std::vector.

2) Non-inheritable classes weren't a feature in C++ until C++11. See Howard Hinnant's answer: https://stackoverflow.com/questions/9298450/are-c11-standard-containers-final
The discussion included the fact that while it may be frowned on to derive from such classes, it is clearly legal to do so in C++98/03. And making it illegal in C++11 would break far too much code.


3) This is why it cannot be used as a base class if you intend to have polymorphic subclasses.

It's still legal, though not suggested, to inherit from it if you aren't using polymorphism (i.e. never call delete on a base-class std::string that has a derived dynamic type).
Last edited on
It is ok to inherit publicly from classes like std::string subject to certain caveats.

More information: http://www.cplusplus.com/forum/general/156923/#msg805416
Thanks alot JLBorges and Ganado for the succinct explanation :)
Well, STL classes have not been designed to be inherited. The major issue with inheriting std::string and others is that they don't have a virtual destructor. That's a big no-no for a base class of public inheritance, as the warning makes clear. It's not nearly as dangerous for private inheritance, though.

More Information visit: https://crbtech.in/online-java-training-course
Last edited on
Topic archived. No new replies allowed.