6

Should a user-defined container that is a wrapper for std::vector, inherit or contain std::vector?

I have a class that is supposed to be a container. I see two options:

1) inherit from vector 2) have a private member vector and override all the vector functions to make my container act as vector

I am not sure if it is only a question of style, or one way is fundamentally better than the other?

The extra functionality I want to add is small, few data members and functions here and there. Mostly it will be convenient functions to work with the data in the vector.

screwnut
  • 1,367
  • 7
  • 26
user3111311
  • 7,583
  • 7
  • 33
  • 48

2 Answers2

10

First of all, STL containers are not supposed to be inherited. They even don't have virtual destructors.

Second, it's always preferable to choose composition/aggregation in favor of inheritance, as this is a lower coupling technique that puts less restrictions/requirements on the code.

See this answer for more details, this question has been raised a lot of times.

Community
  • 1
  • 1
Vladimir Sinenko
  • 4,629
  • 1
  • 27
  • 39
  • "First of all, STL containers are not supposed to be inherited." after that I stopped reading. That is enough for me! – user3111311 Jan 16 '14 at 01:41
0

Interesting read about this topic here - Thou shalt not inherit from std::vector

Unlike what the title suggests, it's OK to inherit from std::vector, in the end it's more an architectural issue. Does it help reuse or code complexity? By doing that, does it make it easier to understand, maintain and debug the code?

Community
  • 1
  • 1
Dannie
  • 2,430
  • 14
  • 16