title: Operator overloading with proxy class
body: <p>I'm learning C++ and this week I try to understand the operator overloading, no problems so far. Now I reached overloading the index operator and I managed it as follows,</p>
  
  <pre><code>std::string &amp;operator[](size_t index);
  std::string const &amp;operator[](size_t index) const;
  </code></pre>
  
  <p>However, in several threads I read it is better to use a Proxy class, so I tried to implement a Proxy class and here the trouble starts. Note that I just implement the Proxy class in this simple class to understand how a Proxy class is working. I have already overloaded all functions without Proxy class and think it is time for the next step.</p>
  
  <p>I have a class Strings which contains a pointer to several string objects. Suppose we have a object of the class Strings, called str, then I want to be able to use str[i] to get the i-th string and str[i][j] to get the j-th letter of the i-th string. Therefore I implemented a operator overloading in the Proxy class for [] and for &lt;&lt;, these are working fine. </p>
  
  <p>Next, I want to be able to say str[i] = str[j], and therefore I implemented the operator=, however I am not able to get this right. Do you see what I'm doing wrong? There is no compile error, but the value isn't updated after calling str[i] = str[j].</p>
  
  <p>And a subquestion, is the Proxy class implemented correct? It is working but I would also like to learn to use the language in a correct way.</p>
  
  <p>Just to avoid confusion: I understand that this is much easier with a vector and that a Proxy class is not needed here. However, I want to understand how a Proxy class works and in my point of view it is best to start implementing it in a very simple class.</p>
  
  <pre><code>class Strings
  {
    std::string *d_str;
  
    public:
      Strings();
      Strings(int argc, char *argv[]);
  
      // Some other functions
      // ...
      // End other functions
  
      class Proxy {
        std::string d_string;
        public:
          Proxy(std::string &amp;str): d_string(str) {}
  
          char &amp;operator[](int j) { return d_string[j]; }
  
          friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;out, Proxy const &amp;rhs)
          {
            out &lt;&lt; rhs.d_string &lt;&lt; '\n';
            return out;
          }
  
          Proxy &amp;operator=(Proxy const &amp;other)
          {
            d_string = other.d_string;
            return *this;
          }
      };
  
      Proxy operator[](size_t idx)
      {
        return Proxy(d_str[idx]); 
      }
  
    private:
      //More functions here
  };
  </code></pre>