title: Class design question - how to provide read only access to class member container
body: <p>In my day-to-day work, I often find myself writing classes like in this simplified example:</p>
  
  <pre><code>class CGarage
  {
  public:
      CGarage();
      ~CGarage();
      typedef std::vector&lt;Car&gt; CarCollection;
  
  private:
      CarCollection m_Cars;
  };
  </code></pre>
  
  <p>I want the users of CGarage to have read only access to the CarCollection. In order to achieve that goal, those are some common solutions which are all not very satisfying:</p>
  
  <p><strong>Solution 1</strong></p>
  
  <pre><code>class CGarage
  {
      Car GetCar(CarCollection::size_type index) const;
      CarCollection::size_type CarCount() const;
  };
  </code></pre>
  
  <p>Main disadvantage:</p>
  
  <ul>
  <li>Lacking iterators, I can't use STL algorithms on Cars (e.g. for_each(...))</li>
  </ul>
  
  <p><strong>Solution 2</strong></p>
  
  <pre><code>class CGarage
  {
      CarCollection::const_iterator CarBegin() const;
      CarCollection::const_iterator CarEnd() const;
      CarCollection::size_type CarCount() const;
  };
  </code></pre>
  
  <p>Main disadvantage:</p>
  
  <ul>
  <li>A lot of boilerplate code if you need support for other iterator types (it, reverse_it).</li>
  </ul>
  
  <p><strong>Solution 3</strong></p>
  
  <pre><code>class CGarage
  {
      const CarCollection GetCars() const;
  };
  </code></pre>
  
  <p>Main disadvantage:</p>
  
  <ul>
  <li>cost of copying CarCollection when returning by value</li>
  <li>implementation details known to users of class (e.g. can't change to std::list without change of breaking user code)</li>
  </ul>
  
  <p><strong>Solution 4</strong></p>
  
  <pre><code>class CGarage
  {
      const CarCollection&amp; GetCars() const;
  };
  </code></pre>
  
  <p>Main disadvantage:</p>
  
  <ul>
  <li>lifetime of CarCollection reference bound to lifetime of CGarage</li>
  <li>implementation details known to users of class</li>
  </ul>
  
  <hr>
  
  <p><strong>Questions</strong></p>
  
  <p>How would you provide read-only access to the CarCollection?</p>
  
  <p>Does your solution change, if CarCollection is a vector with pointers to Car?</p>
  
  <p>If you allow read and write access to the collection, is it acceptable to make the collection public?</p>
  
  <p>Thanks for any advice</p>