title: how to overload accessor and mutator operator[] in c++
body: <p>I want to write a <strong>String</strong> class. And want to use subscript to access element in my <strong>String</strong>. So, I write two member function, one to get the element in the <strong>String</strong>, and another to set the element in the <strong>String</strong>. Please look at following code;</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;algorithm&gt;
  
  using namespace std;
  
  class String {
  public:
      String();
  
      String(const char *s);
  
      char &amp;operator[] (int index);
      char operator[] (int index) const;
  
  private:
      char *arr;
      int len;
  };
  
  String::String() {
      arr = new char[1];
      arr[0] = '\0';
      len = 0;
  }
  
  String::String(const char *s) {
      len = strlen(s);
      arr = new char[len + 1];
      std::copy(s, s + len + 1, arr);
  }
  
  //mutator operator[] ---&gt; used to change data members;
  char&amp; String::operator[](int index)
  {
      cout &lt;&lt; "mutator []" &lt;&lt; endl;
      if (index &gt; len || index &lt; 0)
          throw std::out_of_range("Index out of range");
      return arr[index];
  }
  //Accessor operator[]---&gt; used to read data members
  char String::operator[](int index) const
  {
      cout &lt;&lt; "accessor []" &lt;&lt; endl;
      if (index &gt; len || index &lt; 0)
          throw std::out_of_range("Index out of range");
      return arr[index];
  }
  
  int main()
  {
      String s1 = "abc";
  
      s1[1] = 'b';  //---&gt; should use mutator operator
      String s2 = "efg";
      s2[1] = s1[2]; //---&gt; should use both accessor and mutator operator
      char a = s1[2]; //---&gt; should use accessor operator
      cout &lt;&lt; s2[1] &lt;&lt; endl; //---&gt; should use accessor operator
  }
  </code></pre>
  
  <p>when I run this code. It's outputs are all <code>mutator</code>; It confuses me a lot;</p>