A deep copy constructor creates a new object and allocates separate memory for dynamically allocated members. This ensures that changes in one object do not affect the other.
Example
#include<iostream>
#include<conio.h>
using namespace std;
class hello
{
int a,*p;
public:
hello()
{
a=0;
p=new int;
p=0;
}
hello (int x,int y)
{
a=x;
p=new int;
*p=y;
}
hello (hello &obj)
{
a=obj.a;
p=new int;
*p=*(obj.p);
}
void update()
{
a=a+1;
*p=*p+1;
}
void show()
{
cout<<"\n Value of A:"<<a<< "\t\t value of p:"<<*p;
}
};
int main()
{
hello obj1(10,20);
hello obj2(obj1);//copy constructor by compiler
obj1.show();
obj2.show();
obj1.update();
obj1.show();
getch();
return 0;
}
Output:
Value of A:10 value of p:20
Value of A:10 value of p:20
Value of A:11 value of p:21
int main()
{
hello obj1(10,20);
hello obj2(obj1);//copy constructor by compiler
obj1.show();
obj2.show();
obj1.update();
obj2.show();
getch();
return 0;
}
Output:
Value of A:10 value of p:20
Value of A:10 value of p:20
Value of A:10 value of p:20
When to Use?
- Shallow copy is sufficient when an object does not use dynamically allocated memory.
- Deep copy is required when an object contains pointers to dynamically allocated memory.
No comments:
Post a Comment