title: C++ - overloading [] operator
body: <p>I have a template class Array:</p>
  
  <pre><code>template &lt;class T=int, int SIZE=10&gt;
  class Array {
      T TheArray[SIZE];
  public:
      void Initialize() {
          for (int idx=0; idx &lt; SIZE; idx++) {
              TheArray[idx] = T();
          }
      }
  
      T&amp; operator [](int idx) {
          return TheArray[idx];
      }
  
      T operator [](int idx) const {
          return TheArray[idx];
      }
  }
  </code></pre>
  
  <p>I have some questions on operator <code>[]</code> overloading (I found this example on net).</p>
  
  <p>I understand that <code>T&amp; operator [](int idx)</code> returns a reference to an array value with index <code>idx</code> and that <code>T operator [](int idx) const</code> returns its value.
  However, I am not sure in which case a reference or a value will be returned by using the <code>[]</code> operator.</p>
  
  <p>Also, if I change <code>T operator [](int idx) const</code> -> <code>T operator [](int idx)</code>, the compiler complains. Why is that?
  I can understand that the compiler complains because only the return type is different, but why doesn't it complain when <code>const</code> is added? This only means that none of the class internals are modified, right?</p>
  
  <p>I tried to debug this small main implementation:</p>
  
  <pre><code>int main() {
      int val;
      Array&lt;&gt; intArray;
  
      intArray.Initialize();
      val = intArray[1];
      printf("%d", intArray[1]);
      intArray[1] = 5;
  }
  </code></pre>
  
  <p>And each time <code>T&amp; operator [](int idx)</code> is called. Why?</p>
  
  <p>Thanks in advance.</p>