title: Correct signature for overloading `()` getter and setter for C++ list class?
body: <p>I'm creating a custom <code>double</code> list class. I'd like to overload the <code>()</code> operator so that I can both access elements and assign values to list elements. These functions appear with return types, <code>double</code> and <code>double &amp;</code>, below, respectively in <code>list.h</code>. However, you can see below when I run <code>main.cpp</code>, attempting to use both, only the second <code>operator()</code> is called. I am obviously misunderstanding something -- what is incorrect in my current code, and why is it incorrect?</p>
  
  <blockquote>
    <p>list.h</p>
  </blockquote>
  
  <pre><code>#include &lt;iostream&gt;
  
  class list {
      public:
          // Constructor
          list(int length);
          // Destructor
          ~list();
          // Element accessors
          double operator()(int i) const;
          double &amp; operator()(int i);
      private:
          int length;
          double * data;
  };
  
  list::list(int length) {
      this-&gt;length = length;
      this-&gt;data   = new double[length];
  }
  
  list::~list() { delete [] this-&gt;data; }
  
  double list::operator()(int i) const {
      std::cout &lt;&lt; "()1" &lt;&lt; std::endl;
      return this-&gt;data[i];
  }
  
  double &amp; list::operator()(int i) {
      std::cout &lt;&lt; "()2" &lt;&lt; std::endl;
      return this-&gt;data[i];
  }
  </code></pre>
  
  <blockquote>
    <p>main.cpp</p>
  </blockquote>
  
  <pre><code>#include &lt;iostream&gt;
  #include "list.h"
  using namespace std;
  
  int main() {
      list l(3);
      double x;
  
      // Assign to list element. Should print "()2".
      l(1) = 3;
      // Get list element value. Should print "()1".
      x = l(1);
  
      return 0;
  }
  </code></pre>
  
  <p>After compilation, the program prints:</p>
  
  <pre><code>()2
  ()2
  </code></pre>
  
  <hr>
  
  <h3>Edit</h3>
  
  <p>My problem arose due to the order in which I added the two functions, and some misunderstanding on my part. I first wrote a simple accessor, i.e.:</p>
  
  <pre><code>double list::operator()(int i);
  </code></pre>
  
  <p>Afterwards, I tried to add a "setter" overload:</p>
  
  <pre><code>double &amp; list::operator()(int i);
  </code></pre>
  
  <p>At this point the compiler complained. I searched the web, and without really understanding, added a <code>const</code> keyword after the first function. This stopped the compiler complaints, but then led to the question above. My solution is to eliminate the first overload, i.e., remove:</p>
  
  <pre><code>double operator()(int i) const;
  </code></pre>