title: C++ Operator overload calling destructor
body: <p>For my first try with operator overloading I created a vector class and tried to sum up two vectors. My class contains an array and a vector of int that both contain the same elements.</p>
  
  <p>Addition works fine with the <code>std::vector</code> but I encounter two issues with the array. It seems that the destructor is called at the end of the summing operation which produces a "double free or corruption" error (core dump). Plus, the first two elements of the array are always equal to zero.</p>
  
  <p>Should I also overload the <code>delete</code> or am I missing a thing ?</p>
  
  <p>The header file:</p>
  
  <pre><code>#ifndef MYVECTOR_INCLUDE
  #define MYVECTOR_INCLUDE
  #include &lt;iostream&gt;
  #include &lt;stdexcept&gt;
  #include &lt;cstring&gt;
  #include &lt;vector&gt;
  
  class MyVector {
  public:
      MyVector(int n);
      ~MyVector();
      void set(int idx, int value);
      int get(int idx);
      void print();    
      MyVector &amp;operator=(const MyVector &amp;v);
      MyVector operator+(const MyVector &amp;v);
  private:
      int *data;
      std::vector&lt;int&gt; data_vector;
      int size1;
      int size2;
  };
  #endif
  </code></pre>
  
  <p>The cpp file:</p>
  
  <pre><code>#include "../include/myvector.hpp"
  
  MyVector::MyVector(int n) {
      data = new int [n];
      data_vector.resize(n);
      size1 = n;
      size2 = 1;
  }
  MyVector::~MyVector() {
      if (data != NULL) {
          delete [] data;
      }
  }
  void MyVector::set(int idx, int value) {
      data_vector[idx] = value;
      data[idx] = value;
  }
  int MyVector::get(int idx) {
      return data_vector[idx];
  }
  void MyVector::print() {
      std::cout &lt;&lt; "Vector data" &lt;&lt; std::endl;
      for (int i = 0; i &lt; size1; ++i) {
          std::cout &lt;&lt; data_vector[i] &lt;&lt; " ";
      }
      std::cout &lt;&lt; std::endl;
      std::cout &lt;&lt; "Data" &lt;&lt; std::endl;
      for (int i = 0; i &lt; size1; ++i) {
          std::cout &lt;&lt; data[i] &lt;&lt; " ";
      }
      std::cout &lt;&lt; std::endl;
  }
  MyVector &amp;MyVector::operator=(const MyVector &amp;v) {
      if (this == &amp;v)
          return *this;
      size1 = v.size1;
      size2 = v.size2;
      std::copy(v.data_vector.begin(), v.data_vector.end(), data_vector.begin());
      memcpy(&amp;data, v.data, sizeof(int)*size1);
      return *this;
  }
  MyVector MyVector::operator+(const MyVector &amp;v) {
      if ((size1 == v.size1) &amp;&amp; (size2 == v.size2)) {
          MyVector res = MyVector(size1);
          for (int i = 0; i &lt; size1; ++i) {
              res.data_vector[i] = data_vector[i] + v.data_vector[i];
              res.data[i] = data[i] + v.data[i];
          }
          return res;
      }
      else
          throw std::length_error("Vector dimensions must agree.");
  }
  </code></pre>
  
  <p>Thank you.</p>