title: C++ Operator Overloading [ ] for lvalue and rvalue
body: <p>I made a class Array which holds an integer array. From the main function, I'm trying to get an element of the array in Array using [ ] as we do for arrays declared in main. I overloaded the operator [ ] as in the following code; the first function returns an lvalue and the second an rvalue (Constructors and other member functions are not shown.)</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  class Array {
  public:
     int&amp; operator[] (const int index)
     {
        return a[index];
     }
     int operator[] (const int index) const
     {
        return a[index];
     }
  
  private:
     int* a;
  }
  </code></pre>
  
  <p>However, when I try to call those two functions from main, only the first function is accessed even when the variable is not used as an lvalue. I can't see the point of creating a separate function for an rvalue if everything can be taken care of just by using the lvalue function.</p>
  
  <p>The following code is the main function I used (Operator &lt;&lt; is appropriately overloaded.):</p>
  
  <pre><code>#include "array.h"
  #include &lt;iostream&gt;
  using namespace std;
  
  int main() {
     Array array;
     array[3] = 5;                // lvalue function called
     cout &lt;&lt; array[3] &lt;&lt; endl;    // lvalue function called
     array[4] = array[3]          // lvalue function called for both
  }
  </code></pre>
  
  <p>Is there any way I can call the rvalue function? Is it also necessary to define functions for both lvalue and rvalue?</p>