In: Computer Science
An object copy is a process where a data object has its attributes copied to another object of the same data type.
Shallow Copy :
Deep Copy :
#include <iostream>
using namespace std;
class Engine {
public:
int engineNo;
string engineName;
Engine(int engineNo, string engineName){
this->engineNo = engineNo;
this->engineName = engineName;
}
Engine(Engine *engine){
this->engineNo = engine->engineNo;
this->engineName = engine->engineName;
}
void print(){
cout<<"engineNo : "<<engineNo<<" ";
cout<<"engineName : "<<engineName;
}
};
class Body {
public:
int bodyNo;
string bodyName;
Body(int bodyNo, string bodyName){
this->bodyNo = bodyNo;
this->bodyName = bodyName;
}
Body(Body *body){
this->bodyNo = body->bodyNo;
this->bodyName = body->bodyName;
}
void print(){
cout<<"bodyNo : "<<bodyNo<<" ";
cout<<"bodyName : "<<bodyName<<"\n";
}
};
class Car {
int carId;
Engine *engine;
Body *body;
public:
Car(int carId, Engine *engine, Body *body){
this->carId = carId;
this->engine = engine;
this->body = body;
}
Car(Car *car){
this->carId = car->carId;
this->engine = new Engine(car->engine);
this->body = new Body(car->body);
}
void print(){
cout<<"CarId "<<carId;
cout<<"\nEngine ";
cout<<" stored at memory address : "<<engine<<"\n";
engine->print();
cout<<"\nBody ";
cout<<" stored at memory address : "<<body<<"\n";
body->print();
}
};
int main()
{
Engine *engine = new Engine(1,"engine1");
Body *body = new Body(1,"body1");
Car *car = new Car(1, engine, body);
car->print();
cout<<"COPYING CAR TO CAR1 USING SHALLOW COPY\n";
cout<<"content of car1\n";
Car *car1 = car;
car1->print();
cout<<"COPYING CAR TO CAR2 USING DEEP COPY\n";
cout<<"content of car2\n";
Car *car2 = new Car(car);
car2->print();
return 0;
}
Output :
Notice :
1. In case of shallow copy address of engine and body of car1 and
car is same.
2. In case of deep copy address of engine and body of car2 and car
are different
Do not forget to unvote the answer.
Have a nice day :)