Is copy constructor used for object initialization? How does it works and what is the difference B/W deep copy and shallow copy?
views:
86answers:
1
A:
Hi,
shadow copy : the new object points to the same memory location pointed by the old object, which means that any change of the value of one of the both objects will affect the other one. particulary if you dispose one of the both object, the other will be dispose too.
deep copy : a memory is allocate to the new object and the value in this memory is equals to the value situated at the old object memory location. suitable for objects which have members like table or vector
if you don't write a copy constructor for a class, compiler will write one for you which usually do shadow copy. to write a copy constructor you write like usual constructor but the parameter is a reference to an object of the same class
class B //With copy constructor
{
private:
char *name;
public:
B()
{
name = new char[20];
}
~B()
{
delete name[];
}
//Copy constructor
B(const B &b)
{
name = new char[20];
strcpy(name, b.name);
}
};
Leonzo Constantini
2010-10-03 19:08:28
`strcpy` is not what you want here. (In fact, you don't want `char *` at all, you want `std::string`...)
Oli Charlesworth
2010-10-03 19:12:08
thanks buddy. you have given answer of my question.
ankit
2010-10-03 19:12:53
oli it is not correct one answer.
ankit
2010-10-03 19:14:34