Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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.

like image 934
user3111311 Avatar asked Jan 16 '14 01:01

user3111311


1 Answers

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.

like image 71
Vladimir Sinenko Avatar answered Oct 12 '22 00:10

Vladimir Sinenko