Tuesday, April 13, 2010

Deep Copy vs Shallow Copy in C++

Usually in c++ we will be more confused about these constructors about deep copying & shallow copying.....

Here is a simple example where there is a class called String where we have to strings which is used to store firstname ,lastname and the age of the person.

Where in case of this I am creating the Object of String with the name s1 which after reading the details I am assigning it to one more Object s2.



#include<iostream.h>
#include<string.h>
#include<conio.h>

class String
{
char *firstname; // declaring pointer to store string
char *lastname;
int age;

public:
String()
{
firstname = new char[30];
lastname = new char[30];
age=0;
}
void read()
{
cout<<"\n Enter name:";
cin>>firstname>>lastname;
cout<<"\n age :";
cin>>age;
}
void print()
{
cout<<"\n name is "<<firstname<<" "<<lastname;
cout<<"\n Age :"<<age;
}
~String()
{
delete[]firstname;
delete[]lastname;
}
};

void main()
{
clrscr();

String s1;
s1.read();
s1.print();

String s2=s1; //assigning the object s1 to s2
s2.print();

s1.read();

s1.print();
s2.print();

getch();
}

U can observe after u make any changes to the s1 object with the Strings that is firstname,lastname it will be reflected in s2 object also.

So by default there is one copy constructor given for you in your c++ classes which will be of this prototype which just assigns the values using "=" operator.

Prototype of Copy constructor:
ClassName(ClassName &Object){
}
This is "SHALLOW COPYING"
For the above class :
String(String &s){
firstname=s.firstname;
lastname=s.lastname;
age = s.age;
}

To over come this problem where it should be allocated with the own memory allocations just keep this below code and observe which is called "DEEP COPYING"

String(String &s)
{
cout<<"\n copying......";
int l1= strlen(s.firstname)+1;
int l2= strlen(s.lastname)+1;
firstname = new char[l1];
lastname = new char[l2];
strcpy(firstname,s.firstname);
strcpy(lastname,s.lastname);
age=s.age;
}


SHALLOW COPYING IS DEFAULT DONE .......WHICH OVERLOADS "=" operators.

DEEP COPYING YOU SHOULD WRITE ON YOUR OWN!!

Cheers
Shyamala

No comments:

Post a Comment