Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector_base inheritance vs composition

Tags:

c++

stl

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?

like image 744
FooBant Avatar asked Sep 10 '19 08:09

FooBant


People also ask

Which is the better technique private inheritance or composition?

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."

What is the difference between inheritance and composition in c++?

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.


1 Answers

libc++ uses private inheritance and libstdc++ uses protected inheritance.

Protected and private inheritance is largely a syntactic variant of composition.

like image 200
n. 1.8e9-where's-my-share m. Avatar answered Nov 14 '22 23:11

n. 1.8e9-where's-my-share m.