need of Copy constructor

Hi,
Can some one explain me why is copy constructor use ( or why is copy constructor needed) ?
Sometimes to copy a thing a simple memory copy is not enough. Consider an example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct DynamicArray{
   int* data;
   int size;

   DynamicArray() {
      size = 0;
      data = 0;
   }
   DynamicArray(int sz) {
      size = sz;
      data = new int[size];
   }
   ~DynamicArray() {
      delete data;
   }
};


This is a naive version of std::vector. Now consider what happens here:
1
2
3
4
5
6
7
int main() {
   DynamicArray a(5); //let's say, a.data = 1234
   DynamicArray b;
   b = a; //a plain copy. now b.data = 1234 too
}//end of scope. b is destroyed -> it calls "delete 1234".
// a is destroyed -> it calls "delete 1234" too, but this produces a runtime error, 
// since you can't delete a thing twice. 


To fix this, you need the following copy constructor:
1
2
3
4
5
DynamicArray(const DynamicArray& d) {
   size = d.size;
   data = new int[size];
   std::copy(d.data, d.data+size, data);
}
Now, after the line "b = a", b.data is not the same as a.data and they can both be safely deleted.
Thanks , hamsterman , its clear now . thanks again
Topic archived. No new replies allowed.