« 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 copy6 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 copy7 // this->name = name;89 // deep copy10 this->name = new char[strlen(name) + 1];11 strcpy(this->name, name);12}