SHALLOW COPY: Changes made in the copy of a class object gets reflected onto the original object.
#include<iostream>
#include<cstring>
using namespace std;
public class Car
{
public:
string carid;
int Engine_no;
string Enginename;
string Bodyname;
int Body_no;
~Car()
{
delete carid;
delete Engine_no;
delete Enginename;
delete Bodyname;
delete Body_no;
}
Car(string s, int en, string ename, string bname,
int bn)
{
carid=s;
Engine_no=en;
strcpy( Enginename, ename);
strcpy(Bodyname,
bname);
Body_no=bn;
}
};
int main()
{
string a;int b;string c;string d;int e;
cout<<"Enter the Car Id no.";
cin>>a;
cout<<"Enter the Engine Name";
cin>>c;
cout<<"Enter the Engine no.";
cin>>b;
cout<<"Enter the Body name";
cin>>d;
cout<<"Enter the Body_no";
cin>>e;
Car obj(a,b,c,d,e);//Normal Constructor call
Car obj2=obj;
printf("%s, %d, %s, %s, %d",
obj.carid,obj.Engine_no,obj.Enginename,obj.Bodyname,obj.Body_no);
printf("%s, %d, %s, %s, %d",
obj2.carid,obj2.Engine_no,obj2.Enginename,obj2.Bodyname,obj2.Body_no);
return 0;
}
DEEP COPY: Changes made in the copy of a class object doe not get reflected onto the original object because of two seperate dynamically allocated memory locations.
#include<iostream>
#include<cstring>
using namespace std;
public class Car
{
public:
string carid;
int Engine_no;
string Enginename;
string Bodyname;
int Body_no;
~Car()
{
delete carid;
delete Engine_no;
delete Enginename;
delete Bodyname;
delete Body_no;
}
Car(string s, int en, string ename, string
bname, int bn)
{
carid=s;
Engine_no=en;
strcpy(Enginename,
ename);
strcpy(Bodyname,
bname);
Body_no=bn;
}
Car(Car &s, Car &en, Car
&ename, Car &bname, Car &bn)//assignment of values to
seperate ememory location as reqired by a deep copy
{
carid=s;
Engine_no=en;
strcpy(Enginename,
ename);
strcpy(Bodyname,
bname);
Body_no=bn;
}
};
int main()
{
string a;int b;string c;string d;int e;
cout<<"Enter the Car Id no.";
cin>>a;
cout<<"Enter the Engine Name";
cin>>c;
cout<<"Enter the Engine no.";
cin>>b;
cout<<"Enter the Body name";
cin>>d;
cout<<"Enter the Body_no";
cin>>e;
Car obj(a,b,c,d,e);//Normal Constructor
call
Car obj2=obj;
printf("%s, %d, %s, %s, %d",
obj.carid,obj.Engine_no,obj.Enginename,obj.Bodyname,obj.Body_no);
printf("%s, %d, %s, %s, %d",
obj2.carid,obj2.Engine_no,obj2.Enginename,obj2.Bodyname,obj2.Body_no);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.