8

There are many answers on here saying not to inherit from std::vector and alike such as this question. I understand the reasons and agree with them. However in here Section 4.4.1.2 Bjarne Stroustrup himself inherits from std::vector to add range checking.

Is that a special case, or just something that's ok in that context or something that he really ought not be doing :P

Community
  • 1
  • 1
jcoder
  • 29,554
  • 19
  • 87
  • 130

1 Answers1

4

I think this answer perfectly answers your question.

It's not impossible to inherit from std::vector, it just probably would be very limited (due to no virtual destructor), quite confusing to others and extending by composition would be better/easier/more maintainable than inheritance anyway.

Perhaps Stroustrup simply wanted to show it's doable, but not necessarily to imply that he suggests it.

Community
  • 1
  • 1
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • That makes sense, and you're not at all likely to use vector polymorphicly anyway.. – jcoder Apr 24 '13 at 09:30
  • 2
    @jcoder also note that you can achieve a lot, without most of the pitfalls, by using private inheritance. – juanchopanza Apr 24 '13 at 09:35
  • Interestingly, Stroustrup comes back to the same example again later in his book The C++ Programming Language, in section 16.3.4, where he adds the following warning: "...derivation from a concrete class should be done with care and only rarely because of the lack of virtual functions and run-time type information..." - I would summarize it as follows: it works if you know what you're doing! – trev Jul 20 '21 at 13:11