title: Copy constructor in c++?
body: <p>So I have to write an operator= method in  c++ that copies all the values of one array into another. Here's what I wrote:</p>
  
  <pre><code>dynamic_array &amp;dynamic_array::operator=(const dynamic_array &amp;a) {
      size = a.get_size();
      if (size % BLOCK_SIZE == 0){ //a multiple of BLOCK_SIZE
          allocated_size = size;
      } else {
          int full_blocks = size / BLOCK_SIZE;
          allocated_size  = (full_blocks+1) * BLOCK_SIZE;
      }
      try {
          array = new int[allocated_size];
      } catch (bad_alloc){
          throw exception (MEMORY_EXCEPTION);
      }
  
      //copy a[i..size-1]
      for (int i = 0; i &lt; size; i++){
          array[i] = a[i];
      }
      return *this; //returns a reference to the object
  }
  </code></pre>
  
  <p>So it doesn't assume anything about the sizes and sets the size and allocated size of the array it's given (and using another get_size() method). Now the second code I have to write just says I have to create an array containing a copy of the elements in a. Now I just wrote the same thing as I did for my operator= method (without returning anything):</p>
  
  <pre><code>dynamic_array::dynamic_array(dynamic_array &amp;a) {
      size = a.get_size();
      if (size % BLOCK_SIZE == 0){ //a multiple of BLOCK_SIZE
          allocated_size = size;
      } else {
          int full_blocks = size / BLOCK_SIZE;
          allocated_size  = (full_blocks+1) * BLOCK_SIZE;
      }
      try {
          array = new int[allocated_size];
      } catch (bad_alloc){
          throw exception (MEMORY_EXCEPTION);
      }
  
      //copy a[i..size-1]
      for (int i = 0; i &lt; size; i++){
          array[i] = a[i];
      }
  }
  </code></pre>
  
  <p>Now this is giving me the output that I want but I'm just wondering if there's an easier way to do these two methods. The methods are for a dynamic array and I feel like there's more lines of code than needed. The operator= one is supposed to copy the elements of a into a new dynamic array and <code>dynamic_array::dynamic_array(dynamic_array &amp;a) {</code> is supposed to create a new array containing a copy of the elements in a. It sounds like the same code for each method because you always need to create a new array and you will always need to copy the array elements from one array to another but is there a more simpler way to write these two methods or is this the simplest way to do it? </p>