title: Returning a const reference to vector of an object
body: <p>I have 2 questions related to the same problem:</p>
  
  <ol>
  <li><p>How can I return a reference to a vector which belongs to a class?</p>
  
  <p>I have this class:</p>
  
  <pre><code>class sys{
      protected:
          vector&lt;int&gt; s;
  
      public:
          sys();
          vector&lt;int&gt;&amp; getS() {return s;} //(1)
  };
  </code></pre>
  
  <p>(1) should return the reference of the vector <code>s</code>. However, in <code>main()</code>:</p>
  
  <pre><code>main(){
      sys* my_sys = new sys();
      vector&lt;int&gt; &amp;t1  = my_sys-&gt;getS(); //(2)
      vector&lt;int&gt; t2 = my_sys-&gt;getS(); //(3)
      ...
  }
  </code></pre>
  
  <ul>
  <li><code>t1</code> is a reference to <code>s</code> (i.e. when <code>t1</code> is changed <code>my_sys.s</code> is changed as well).</li>
  <li><code>t2</code> is a COPY of <code>s</code> (i.e. when <code>t2</code> is changed my_sys.s is NOT changed).</li>
  </ul>
  
  <p>Why does line (3) work?</p></li>
  <li><p>I do not want it to be possible to change <code>my_sys.s</code> outside of the class, but I want to return a reference because of efficiency. Where do I put the <code>const</code>?</p>
  
  <p>I tried to change line (1) to</p>
  
  <pre><code>const vector&lt;int&gt;&amp; getS() {return s;} //(4)
  </code></pre>
  
  <p>but I am not sure if that is enough.</p></li>
  </ol>