title: Array Subscription: returning Reference vs proxy class method
body: <p>While searching for methods for overloading Subscript('[]') operator for template class, I came across two different techniques.</p>
  
  <p>First Technique:</p>
  
  <p>Overloading the <code>operator []</code> returning pointer to the container directly, which will allow both reading value and assigning value. A sample implementation of this technique:</p>
  
  <pre><code>template &lt;class T&gt;
  class X
  {
      int _size;
      T *container;
  public:
      X(int sz)
      {
          _size=sz;
          container=new T[sz]();
      }
      ~X()
      {
  
      }
  
      T&amp; operator [](int indx)
      {
          return container[indx];
      }
  
  };
  </code></pre>
  
  <p>With <code>main()</code> as:</p>
  
  <pre><code>X&lt;int&gt; sample(100);
  cout&lt;&lt;sample[9]&lt;&lt;endl;
  sample[9]=9;
  cout&lt;&lt;sample[9]&lt;&lt;endl;
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>0
  9
  </code></pre>
  
  <p>Second Technique:</p>
  
  <p>Second technique involves declaring a proxy class and overloading the <code>operator =</code> via that class. A sample implementation of this technique:</p>
  
  <pre><code>template &lt;class T&gt;
  class X
  {
      int _size;
      T *container;
  public:
      X(int sz)
      {
          _size=sz;
          container=new T[sz]();
      }
      ~X()
      {
  
      }
  
      class Proxy
      {
          int indx;
          X&lt;T&gt; &amp;parent;
      public:
          Proxy(X&lt;T&gt; &amp;p, int x) : parent(p),indx(x)
          {
  
          }
          void operator =(T assgn)
          {
              parent.container[indx]=assgn;
          }
          operator T const &amp;()
          {
              return parent.container[indx];
          }
          friend class X&lt;T&gt;;//unnecessary line, I know!
      };
      Proxy operator[](int indx)
      {
          return Proxy(*this,indx);
      }
  
  };
  </code></pre>
  
  <p>With same <code>main()</code> we get same output.</p>
  
  <p>I personally like the second method. But, I really want to compare these two methods. What are the major functional difference of these two techniques. What advantages each of these method have?</p>