MD.
ABU ARMAN
ID :221311044
COURSE T-:OOP LANGUAGE
DEPT OF CSE
VARENDRA UNIVERSITY
RAJSHAHI
Shallow Copy and Deep Copy
in C++
Shallow Copy
SHALLOW COPY IS EASY ,WE DON’T
} NEED TO WRITE ANY CODE.
#include<iostream>
#include<conio.h> };
using namespace std; int main(){
class u{ u ob1(23,12);
int a,b; u ob2(ob1);
public:
u(int x,int y){ ob1.disp();
a=x; getch();
b=y; ob2.disp();
} getch();
void disp(){
cout<<"a="<<a<<"\n"<<"b="<<b<<"\n"; return 0;
}
Shallow copy Explain
#include<iostream> };
#include<conio.h> int main(){
using namespace std; u ob1(23,12);
class u{ u ob2(ob1);
int a,b;
public:
ob1.disp();
} getch();
u(int x,int y){ ob2.disp();
a=x; getch();
a=23;
b=y; b=12;
}
void disp(){
return 0; } CLASS
a=23;
cout<<"a="<<a<<"\n"<<"b="<<b<<"\n"; obj1 b=12;
}
obj2
SHALLOW COPY
int main(){
u ob1(23,12);
u ob2(ob1); COPY CONSTACTOR WILL DO COPY.
ob1.disp();
getch();
ob2.disp();
getch();
return 0; }
SHALLOW COPY
#include<iostream> u ob1(23,12);
#include<conio.h> u ob2(ob1);
Copy Constractor DO THIS
using namespace std; u ob3=ob1;
COPY
class u{ u ob4;
int a,b; ob4=ob1; ASSIGNMENT
public: ob1.disp(); OPERATOR DO THIS
DEFAULT getch(); COPY
u(){} CONSTRACTOR ob2.disp();
u(u &t){ getch();
a=t.a; ob3.disp();
Copy constractor
getch();
b=t.b;}
ob4.disp();
u(int x,int y){
return 0; COMPILER AUTO WRITE THIS
a=x;
} CODE.
b=y; }
void disp(){cout<<"a="<<a<<"\ WE DONT NEED TO WREITE
n"<<"b="<<b<<"\n; } THIS CODE MANUALLY & THIS
}; IS CALLED SHALLOW COPY
int main(){
DEEP COPY
WHEN WE WRITE TO CODE COPYING OBJECTS
MANUALLY,
THEN IT’S GOING TO BE DEEP COPY
DEEP COPY
#include<iostream> void disp(){
#include<conio.h> cout<<"a="<<a<<"\n"<<"b="<<b<<"\n"<<"*p="<<*p<<"\n";
using namespace std;
class u{ This is why we are }
int a,b,*p; writing this code
public: };
u(){
manually int main(){
p=new int; u ob1;
} ob1.get(1,2,3);
u(u &t){ u ob2=ob1;
a=t.a; *p ob1.disp();
b=t.b; ob2.disp();
p=new int; ob1.get(2,4,4);
*p=*(t.p); ob1.disp();
p
ob2.disp();
}
void get(int x,int y,int z){
a=x;
b=y; return 0;
*p=z; }
}