Ok, this is really difficult to confess, but I do have a strong temptation at the moment to inherit from std::vector
.
I need about 10 customized algorithms for vector and I want them to be directly members of the vector. But naturally I want also to have the rest of std::vector
's interface. Well, my first idea, as a law-abiding citizen, was to have an std::vector
member in MyVector
class. But then I would have to manually reprovide all of the std::vector's interface. Too much to type. Next, I thought about private inheritance, so that instead of reproviding methods I would write a bunch of using std::vector::member
's in the public section. This is tedious too actually.
And here I am, I really do think that I can simply inherit publicly from std::vector
, but provide a warning in the documentation that this class should not be used polymorphically. I think most developers are competent enough to understand that this shouldn't be used polymorphically anyway.
Is my decision absolutely unjustifiable? If so, why? Can you provide an alternative which would have the additional members actually members but would not involve retyping all of vector's interface? I doubt it, but if you can, I'll just be happy.
Also, apart from the fact that some idiot can write something like
std::vector<int>* p = new MyVector
is there any other realistic peril in using MyVector? By saying realistic I discard things like imagine a function which takes a pointer to vector ...
Well, I've stated my case. I have sinned. Now it's up to you to forgive me or not :)
std::vector<int>* p = new MyVector
doesn't really work in the first place, because std::vector does not have a virtual destructor. There will most certainly be undefined behavior in the near future. – Lattenstd::vector
's interface is quite huge, and when C++1x comes along, it will greatly expand. That's a lot to type and more to expand in a few years. I think this is a good reason to consider inheritance instead of containment - if one follow the premise that those functions should be members (which I doubt). The rule to not to derive from STL containers is that they aren't polymorphic. If you aren't using them that way, it doesn't apply. – LandisD
contain aB
instead of inheriting from it to avoid the risk of "accidental polymorphism" (having aD
object treated as aB
and breaking those invariants), even though it's more work. – Region