Alex Rivera | Logout

Can you extend the standard library by inheritance?

Asked 2009-07-02T11:58:37.877
61

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:

  1. Are there any other standard library classes which are intended to be derived from?

  2. 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's what() member function did not return a NTBS (say it returned a null pointer) be standard conforming?

Edit
Report

1 Answer

5

The C++ standard library isn't a single unit. It is the result of combining and adopting several different libraries (a large chunk of the C standard library, the iostreams library and the STL are the three main building blocks, and each of these have been specified independently)

The STL part of the library is generally not meant to be derived from, as you know. It uses generic programming, and generally avoids OOP.

The IOStreams library is much more traditional OOP, and uses inheritance and dynamic polymorphism heavily internally --- and users are expected to use the same mechanisms to extend it. Custom streams are typically written by deriving from either the stream class itself, or the streambuf class it uses internally. Both of these have virtual methods that can be overridden in derived classes.

std::exception is another example.

And like D.Shawley said, I would apply the LSP to your second question. It should always be legal to substitute the base class for a derived one. If I call exception::what(), it must follow the contract specified by the exception class, no matter where the exception object came from, or whether it is actually a derived class having been upcasted. And in this case, that contract is the standard's promise of returning a NTBS. If you made a derived class behave differently, then you'd violate the standard because an object of type std::exception no longer returns a NTBS.

answered 2009-07-02T12:24:45.623

Your Answer