It is a commonly held belief that the the C++ standard library is not generally intended to be extended using inheritance. Certainly, I (and others) have criticised people who suggest deriving from classes such as std::vector. However, this question: Can what() return NULL for exceptions? made me realise that there is at least one part of the Standard Library that is intended to be so extended – std::exception.
So, my question has two parts:
-
Are there any other standard library classes which are intended to be derived from?
-
If one does derive from a standard library class such as
std::exception, is one bound by the interface described in the ISO Standard? For example, would a program which used an exception class who’swhat()member function did not return a NTBS (say it returned a null pointer) be standard conforming?
Good nice question. I really wish that the Standard was a little more explicit about what the intended usage is. Maybe there should be a C++ Rationale document that sits alongside the language standard. In any case, here is the approach that I use:
(a) I’m not aware of the existence of any such list. Instead, I use the following list to determine whether a Standard Library type is likely to be designed to be inherited from:
virtualmethods, then you shouldn’t be using it as a base. This rules outstd::vectorand the like.virtualmethods, then it is a candidate for usage as a base class.friendstatements floating around, then steer clear since there is probably an encapsulation problem.std::char_traits) is a pretty good clue that you shouldn’t be using it as a base.Unfortunately I don’t know of a nice comprehensive or black and white list. I usually go by gut feel.
(b) I would apply LSP here. If someone calls
what()on your exception, then it’s observable behavior should match that ofstd::exception. I don’t think that it is really a standards conformance issue as much as a correctness issue. The Standard doesn’t require that subclasses are substitutable for base classes. It is really just a “best practice”.