title: C++ helper function for copy constructor
body: <p>I haven't been able to find a good answer to this question.</p>
  
  <p>I'm working on a C++ program and I'm trying to implement a function named <strong>copy</strong> which takes a reference to another object as an argument.  Then, it returns a deep copy of this object.</p>
  
  <p>Some background on my project: the <strong>Scene</strong> class contains a dynamic array (called "Images") of pointers to either NULL or an instance of the <strong>Image</strong> class, which is not shown here - but works as it should (it inherits all of its methods from a third party library, EasyBMP)</p>
  
  <p>The reason I'm doing this is to avoid duplicating code in two places, but it's very possible that I'm taking the wrong approach.</p>
  
  <p>I call this function in my assignment operator:</p>
  
  <pre><code>Scene const &amp; Scene::operator=(Scene const &amp; source)
  {
      if (this != &amp;source) {
          clear();
          copy(source);
      }
      return *this;
  }
  </code></pre>
  
  <p>And my copy constructor: </p>
  
  <pre><code>Scene::Scene(Scene const &amp; source)
  {
      copy(source);
  }
  </code></pre>
  
  <p>Finally, my copy() method looks like this:</p>
  
  <pre><code>Scene const &amp; Scene::copy(Scene const &amp; source)
  {
      Scene res(source.Max);
      for (int i=0; i&lt;res.Max; i++)
      {
          delete res.Images[i];
          if (source.Images[i] != NULL) 
              res.Images[i] = new Image(*(source.Images[i]));
          else
              res.Images[i] = NULL;
      }   
  
      return res;
  }
  </code></pre>
  
  <p>Currently, it does NOT work.  One problem I can see is that I'm trying to return a variable that goes out of scope as soon as the copy function ends. I tried returning a reference before, but the compiler threw errors and this wouldn't help with the scope issue anyways.</p>
  
  <p>But I'm not even sure that my logic is right, i.e. can you even do something like this in a constructor?  Or should I just explicitly write out the code in the copy constructor and assignment operator (without implementing the helper method <em>copy</em>)?</p>
  
  <p>I'm very new to C++ and pointers, so any guidance would be much appreciated.</p>