title: C++ Destructors , dynamic allocation
body: <p>I have recently had some errors (bad_alloc) due to my lack of a destructor. </p>
  
  <p>I currently have two classes, set up in this way:</p>
  
  <pre><code>class ObjOne {
  friend class ObjTwo;
  public:                  //constructors and some other random methods
      ObjOne(int n) {
      }
  
      ObjOne() {
      }
  
  private:
      int currSize;
      int size;
      int *jon;
  };
  
  
   class ObjTwo {
   public:                       //constructors and some other methods
       ObjTwo(ObjOne, int n) {}  //
       ObjTwo() {}
       ObjTwo(const ObjTwo &amp;source) {    //copy constructor
          num = source.num;
          x = source.x;
          myObjOne=source.myObjOne;
       }
       ~ObjTwo() {                          //destructor
             delete &amp;num;
             delete &amp;x;
             delete &amp;myObjOne;
        }
  
  
  private:
      ObjOne myObjOne;
      int num, x;
  };
  </code></pre>
  
  <p>and here is my operator= for ObjTwo</p>
  
  <pre><code>ObjTwo&amp; ObjTwo::operator=(const ObjTwo&amp; other) {
      num = source.num;
      x = source.x;
      myObjOne=source.myObjOne;
      return *this;
  }
  </code></pre>
  
  <p>Firstly, my assumptions were (Please correct these if it is incorrect):</p>
  
  <p>ObjOne does NOT need a destructor, as it is only primitive types, and when the compiler will use the default destructor to clean it up.
  ObjTwo DOES need a destructor, as it contains ObjOne
  ObjTwo Destructor will need to deallocate memory from x,num and myObjOne.</p>
  
  <p>I have made a few attempts at destructors with this, however I still run into bad_alloc errors (when testing with huge loops etc.) or other errors (with the current one it just crashes when destructor is called).</p>
  
  <p>Any guidance on what I am doing wrong is appreciated</p>
  
  <p>EDIT:
  I have a bad_alloc exception being thrown when I simply put this in a loop:</p>
  
  <pre><code>ObjTwo b(//some parameters);
  ObjTwo a(//some parameters);
  for (int i=0; i&lt;20000000; i+) {
      bool x = (a == b);
  }
  </code></pre>
  
  <p>and this is overloaded == operator</p>
  
  <pre><code>bool ObjTwo::operator==(const ObjTwo&amp; other) {
  
  ObjTwo temp = other;
  
  for(int i=myObjOne.x; i&gt;=0; i--) {
      if(myObjOne.get(i)!=temp.myObjOne.get(i)) {
          return false;
      }
  }
  return true;
  }
  </code></pre>
  
  <p>After some reading on the error it seemed that it was caused to due running out of memory; which my unfunctioning destructor would cause. What could be the problem here?</p>
  
  <p>and the get method simply returns jon[i];</p>