title: Const and Non-Const Operator Overloading
body: <p>I have a topic I'm confused on that I need some elaborating on. It's operator overloading with a const version and a non-const version.</p>
  <pre><code>// non-const
  double &amp;operator[](int idx) {
      if (idx &lt; length &amp;&amp; idx &gt;= 0) {
          return data[idx];
      }
      throw BoundsError();
  }
  </code></pre>
  <p>I understand that this lambda function, takes an index and checks its validity and then returns the index of the array data in the class. There's also a function with the same body but with the function call as</p>
  <pre><code>const double &amp;operator[](int idx) const
  </code></pre>
  <p>Why do we need two versions?</p>
  <p>For example, on the sample code below, which version is used in each instance below?</p>
  <pre><code>Array a(3);
  a[0] = 2.0;
  a[1] = 3.3;
  a[2] = a[0] + a[1];
  </code></pre>
  <p>My hypothesis that the const version is only called on <code>a[2]</code> because we don't want to risk modifying <code>a[0]</code> or <code>a[1]</code>.</p>
  <p>Thanks for any help.</p>