title: how to add (operator+) two objects correctly in c++
body: <p>Im trying to add to objects of class Vector1
  Vector1 has:</p>
  
  <pre><code>int dim; // the dimension 
  int *x; // the values of all dimensions.
  </code></pre>
  
  <p>when constructed the user can set the dim and all the values.</p>
  
  <p>Now i try to do this in main:</p>
  
  <p>cout &lt;&lt; (vector1 + vector2)[i]; // print x[i] of the sum.</p>
  
  <p>to do this I overloaded both + and [] operators, but Im not sure of how to do + correctly</p>
  
  <p>/////////////
  At first I thought I would do:</p>
  
  <pre><code>Vector1 &amp;Vector1::operator+(const Vector1 &amp;v2) {
      if (dim == v2.dim) 
      {
          for (int i=0 ; i&lt;dim ; i++)
              x[i] = x[i] + v2.x[i];
      }
      else {
          cout &lt;&lt; "Error! Vectors from different dimensions";
          exir(1);
      }
      return *this;
  }
  </code></pre>
  
  <p>but then I realized that Im overwriting Vector1 this way, I want to be able to get the solution without overwriting any data so I thought of this:</p>
  
  <pre><code>Vector1 &amp;Vector1::operator+(const Vector1 &amp;v2) {
      Vector1 temp;
      if (dim == v2.dim) 
      {
          temp.dim = dim;
          int *arr = new int[dim];
          for (int i=0 ; i&lt;dim ; i++)
              arr[i] = x[i] + v2.x[i];
      }
      else 
      {
          cout &lt;&lt; "Error! Vectors from different dimensions";
          exit(1);
      }
      return temp;
  }
  </code></pre>
  
  <p>now im not sure if the "temp" vector I'm returning will be deleted after the "cout &lt;&lt; ..." line or that it will stay in memory even though Im not using it anymore...</p>
  
  <p>Can someone explain to me how to do this correctly?</p>
  
  <p>Thnx  </p>