« Shallow Copy And Deep Copy

Shallow Copy

When we pass array as argument than rather than copying the entire array only the address of the first element of the array is copied. This is called Shallow Copy. Ideally we would have created new array and copied entire array values into this new array.

1Student(int age, char *name)
2{
3 cout << "constructor 3 called" << endl;
4 this->age = age;
5 // shallow copy
6 this->name = name;
7}

Deep Copy

Here new array is created and array values are copied into this new array.

1Student(int age, char *name)
2{
3 cout << "constructor 3 called" << endl;
4 totalStudents++;
5 this->age = age;
6 // shallow copy
7 // this->name = name;
8
9 // deep copy
10 this->name = new char[strlen(name) + 1];
11 strcpy(this->name, name);
12}