user defined copy constructor doubt

Well, I have understood bit-wise copy very well but still not getting my hands on deep copy. I have understood the mechanism, but not able to implement it in a program.
I am trying following code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<iostream>
#include<algorithm>
using namespace std;

class array
{
  public:
  int size;
  int* data;

//constructor
 array(int size)
 {
   cout << "calling constructor\n"<<endl;

   this->size = size; //5

  cout << "this->size is\n"<<this->size<<endl;

   this->data = new int[size];

  cout << "this->data is\n"<<this->data<<endl; //address
 }

//copy constructor

 array(array& object)
{
  cout << "calling copy constructor\n"<<endl;
  size = object.size;

  cout << "size is\n"<<object.size<<endl; //5

  data = new int[object.size];
  cout<<"data is\n"<<data<<endl; //next address
}

 ~array()
{
  cout << "calling destructor\n"<<endl;
  delete [] data;
}

};
int main()
{
 array first(5);
 first.data[0]=20;

 {
   array copy=first;

  cout << "first element is\n"<<first.data[0]<<endl  //20
  cout <<"copied element is\n"<<copy.data[0]<<endl;   //gives 0
}

 first.data[0]=30;

return 0;
}


obvious reason is, I dint copy data in copy constructor hence it is giving value 0 instead of 20

so I try something like
1
2
3
4
5
6
 array(array& object)
{
 //previous code then
copy(copy.data,copy.data+copy.size,data); //which is not correct syntax but I
//don't know how to copy data
}


so I get an error like

explicit_copy_constructor.cpp:37:12: error: ‘std::copy’ does not have class type


could somebody please let me know how should I make value of copy.data[0] 20?
Thanks in advance.
1
2
3
4
5
6
7
8
9
10
11
12
 array(array& object)
{
  cout << "calling copy constructor\n"<<endl;
  size = object.size;

  cout << "size is\n"<<object.size<<endl; //5

  data = new int[size];
  for( int i = 0 ; i < size ; i++)
	  data[i] = object.data[i];
  cout<<"data is\n"<<data<<endl; //next address
}
Last edited on
or you could use memcpy (mere binary copy)

1
2
data = new int[size];
memcpy(data, object.data, size * sizeof(int));
And usually optimized.
This topic discusses some alternative ways to copy arrays. I wouldn't mind the actual time benchmarking [especially mine because apparently they were bogus], but I thought I'd link it because of the code examples.

http://www.cplusplus.com/forum/beginner/56219/
@bluecoder :perfect ! thanks a lot. It now works. :)
@johnbob - do I need to include any header file for memcpy (I guess it is a C function, though not sure). It gives the error, error: ‘memcpy’ was not declared in this scope
Thanks in advance.

It's in memory.h (or string.h, or cstring, if you already use those).
@gaminic - thanks for the information. It's in <cstring> :)
Topic archived. No new replies allowed.