Hi,
A good place to implement a copy constructor is when your class has a string variable or any other dynamically allocated memory.
As Disch mentioned, if the default copy constructor is called, the new object's pointer variables will contain the same address as that of the original object's pointer variable.
So, if you make changes in one, it will reflect in the other and that sort of defeats the purpose of copying.
E.g:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class str
{
char *s;
str()
{
s=new char[256];
}
~str()
{
delete s;
}
str (str& _str)
{
s = new char[256];
strcpy(s, _str.s);
}
};
|
If the copy constructor wasn't there and then the original copy constructor wouldn't have allocated a new memory and copied the string. Instead, it would have assigned the address contained in s to the new object.
So, if you changed the value of s in one object, it would have reflected in the new object too.
So here it is necessary to explicitly define a copy constructor.