A shallow copy constructor creates a copy of an object by copying its members as is, including pointers. This means that if the object contains a pointer to dynamically allocated memory, both the original and copied objects will point to the same memory location. Consequently, modifying one object will 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;
}
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:

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:21
Problems with Shallow Copy
- Both objects share the same dynamically allocated memory.
- If one object modifies the data, it reflects in the other.
- When one object is destroyed, the pointer in the other object becomes a dangling pointer, leading to undefined behavior.
No comments:
Post a Comment