A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.
A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.
I am giving you one example which perform deep copy in this example if you do not override copy constructor then it will give run time error, not perform as what we want so it will be help full for understanding why we have tooverride copy constructor if compiler provide it by default.
class base
{
int *a;
public:
base()
{}
void allocate()
{
a = new int(10);
}
void disp()
{
cout<<*a<<endl;
}
base(base &b)
{
a = new int(*(b.a));
}
~base()
{
delete a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
base *b1 = new base;
b1->allocate();
base *b2 = new base(*b1);
b1->disp();
delete b1;
b2->disp();
delete b2;
return 0;
}
you might have forgotten to add zero parameter constructor, but your code is really nice one.
it helps me alot. thanks......... ..
Originally posted by mailbankey
Hi All,
I am giving you one example which perform deep copy in this example if you do not override copy constructor then it will give run time error, not perform as what we want so it will be help full for understanding why we have tooverride copy constructor if compiler provide it by default.
class base
{
int *a;
public:
base()
{}
void allocate()
{
a = new int(10);
}
void disp()
{
cout<<*a<<endl;
}
base(base &b)
{
a = new int(*(b.a));
}
~base()
{
delete a;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
base *b1 = new base;
b1->allocate();
base *b2 = new base(*b1);
b1->disp();
delete b1;
b2->disp();
delete b2;
return 0;
}
Comment