Note that there are some explanatory texts on larger screens.

plurals
  1. POIs it okay to inherit implementation from STL containers, rather than delegate?
    text
    copied!<p>I have a class that adapts std::vector to model a container of domain-specific objects. I want to expose most of the std::vector API to the user, so that he/she may use familiar methods (size, clear, at, etc...) and standard algorithms on the container. This seems to be a reoccurring pattern for me in my designs:</p> <pre><code>class MyContainer : public std::vector&lt;MyObject&gt; { public: // Redeclare all container traits: value_type, iterator, etc... // Domain-specific constructors // (more useful to the user than std::vector ones...) // Add a few domain-specific helper methods... // Perhaps modify or hide a few methods (domain-related) }; </code></pre> <p>I'm aware of the practice of preferring composition to inheritance when reusing a class for implementation -- but there's gotta be a limit! If I were to delegate everything to std::vector, there would be (by my count) 32 forwarding functions!</p> <p>So my questions are... Is it really so bad to inherit implementation in such cases? What are the risks? Is there a safer way I can implement this without so much typing? Am I a heretic for using implementation inheritance? :)</p> <p><strong>Edit:</strong></p> <p>What about making it clear that the user should not use MyContainer via a std::vector&lt;> pointer:</p> <pre><code>// non_api_header_file.h namespace detail { typedef std::vector&lt;MyObject&gt; MyObjectBase; } // api_header_file.h class MyContainer : public detail::MyObjectBase { // ... }; </code></pre> <p>The boost libraries seem to do this stuff all the time.</p> <p><strong>Edit 2:</strong></p> <p>One of the suggestions was to use free functions. I'll show it here as pseudo-code:</p> <pre><code>typedef std::vector&lt;MyObject&gt; MyCollection; void specialCollectionInitializer(MyCollection&amp; c, arguments...); result specialCollectionFunction(const MyCollection&amp; c); etc... </code></pre> <p>A more OO way of doing it:</p> <pre><code>typedef std::vector&lt;MyObject&gt; MyCollection; class MyCollectionWrapper { public: // Constructor MyCollectionWrapper(arguments...) {construct coll_} // Access collection directly MyCollection&amp; collection() {return coll_;} const MyCollection&amp; collection() const {return coll_;} // Special domain-related methods result mySpecialMethod(arguments...); private: MyCollection coll_; // Other domain-specific member variables used // in conjunction with the collection. } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload