Short Question:
Is there a reason why C++ STL implementations use a vector_base
struct/class (to handle resources and allocators) as a base class of std::vector
rather than using composition?
Longer Version:
In my "quest" to improve my knowledge of C++ I've been trying to re-implement a Vector
class, mostly std::
compliant. I think I've understood well enough why is sensible to use allocators and why you'd actually want all the memory handling in a separate class/struct (RAII and all that) but I fail to see why would we want std::vector
to inherit from that class rather than having it as a private member.
LLVM and gcc both use inheritance for example.
I find, on the other hand, that constructors and assignments operators (especially the move
-types) are much easier to handle using composition.
Am I only exposing my superficial knowledge of the language?
As an example I searched through some textbook and I found that Stroustroup's books have different versions of his "mock re-implementations" of the standard (just to confuse me more!) with his 2013 book "The C++ Programming language, 4th ed." using composition and his 2014 "Programming: Principles and Practice, 2nd ed." using inheritance!
Anyone can help me shed some light?
It's usually inferior to composition" "If you make a class D privately inherit from a class B, you do so because you are interested in taking advantage of some of the features available in class B, not because there is any conceptual relationship between objects of types B and D."
Composition is in contrast to inheritance, it enables the creation of complex types by combining objects (components) of other types, rather than inheriting from a base or parent class. To put it simply, composition contains instances of other classes that implement the desired functionality.
libc++ uses private inheritance and libstdc++ uses protected inheritance.
Protected and private inheritance is largely a syntactic variant of composition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With