开发者

Is copy constructor used for object initialization? How does it works and what is the difference B/W deep copy and shallow copy?

开发者 https://www.devze.com 2023-01-19 01:10 出处:网络
Is copy constructor used for object initialization? How does it works and what is the difference B/W deep copy and shallow co开发者_运维问答py? The copy constructor is used to initilize the new object

Is copy constructor used for object initialization? How does it works and what is the difference B/W deep copy and shallow co开发者_运维问答py?


The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors in C++.


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);
       }
  };
0

精彩评论

暂无评论...
验证码 换一张
取 消