Monday 27 June 2016

When to use our own copy constructor while compiler already provides it


Actually compiler provided copy constructor copies all the values of members. So we are using a dynamic allocated member then only address of that member is copied in new object's member. It does not allocate new memory.

  1. #include <iostream>
  2. #include<cstring>
  3. #include<cstdio>
  4. using namespace std;
  5. class XYZ
  6. {
  7.     public:
  8.     char *p;
  9.     XYZ(char *name,int l){
  10.         p=new char[l+1];
  11.         strcpy(p,name);
  12.        
  13.     }
  14. };
  15. int main() {
  16.     XYZ obj1("str",3);
  17.     printf("content of obj1.p is : %u\n",obj1.p);
  18.     XYZ obj2=obj1;
  19.     printf("content of obj2.p is : %u",obj2.p);
  20. }
So here content of member p of obj1 and obj2 is same which is base address of string str
Note that memory is allocated once and pointer to that memory is set for both objects. So default copy constructor only copying members value that is value of obj1.p ( which is address of string "str" ) is copied to obj2.p


  1. #include <iostream>
  2. #include<cstring>
  3. #include<cstdio>
  4. using namespace std;
  5. class XYZ
  6. {
  7.     public:
  8.     char *p;
  9.     XYZ(char *name,int l){
  10.         p=new char[l+1];
  11.         strcpy(p,name);
  12.        
  13.     }
  14.     ~XYZ(){
  15.         delete p;
  16.     }
  17. };
  18. int main() {
  19.     // your code goes here
  20.     XYZ obj1("str",3);
  21.     {
  22.         XYZ obj2=obj1;     //default copy constructor called
  23.     }
  24.     cout<<obj1.p;    // it will cause error since string "str" is already deleted
  25. }

So in such cases we need our own copy constructor which allocate a new memory for obj2 whose base address is stored in member pointer p.

1 comment:

  1. This guide is very interesting and useful for professional promotion. Actually compiler provided copy constructor copies all the values of members. The latest review of Paper rater contains information that the default copy constructor only copying members value that is value. So we are using a dynamic allocated member then only address of that member is copied in new object's member.

    ReplyDelete

THANKS FOR UR GREAT COMMENT

Blogger Widgets