saneha
04-29-2011, 08:19 AM
differetiate between shallow copy and copy constructor with examples?
Vuhelper
04-29-2011, 08:19 AM
Default copy constructor uses shallow copy
Overloaded copy constructor uses deep copy
Shallow copy example:
Student::Student (const Student & obj) { //copy constructor with sallow copy
rollNo=obj.rollNo;
name=obj.name;
GPA=obj.GPA;
}
int main ( ) {
Student studentA;
Student studentB=studentA; /* Shallow copy: compiler will use copy constructor to assign studentA values to newly created object studentB */
}
Deep copy example:
Student::Student(const Student & obj) { //copy constructor with deep copy
name=new char[strlen(obj.name)+1];
Strcpy(name, obj.name);
}
int main() {
Student studentA;
Student studentB=studentA;/* Deep copy: compiler will use copy constructor to assign studentA values to newly created object studentB */
}
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.