- #include <iostream>
- #include<cstring>
- #include<cstdio>
- using namespace std;
- class XYZ
- {
- public:
- char *p;
- XYZ(char *name,int l){
- p=new char[l+1];
- strcpy(p,name);
- }
- };
- int main() {
- XYZ obj1("str",3);
- printf("content of obj1.p is : %u\n",obj1.p);
- XYZ obj2=obj1;
- printf("content of obj2.p is : %u",obj2.p);
- }
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
- #include <iostream>
- #include<cstring>
- #include<cstdio>
- using namespace std;
- class XYZ
- {
- public:
- char *p;
- XYZ(char *name,int l){
- p=new char[l+1];
- strcpy(p,name);
- }
- ~XYZ(){
- delete p;
- }
- };
- int main() {
- // your code goes here
- XYZ obj1("str",3);
- {
- XYZ obj2=obj1; //default copy constructor called
- }
- cout<<obj1.p; // it will cause error since string "str" is already deleted
- }
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.
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