#include <iostream>
using namespace std;
class Car{
public:
string name;
string color;
int *mileage;
Car(string name, string color) {
this->name = name;
this->color = color;
mileage = new int; // dynamic allocation
*mileage = 12; // value allocated
}
Car(Car &original) {
cout << "copying original to new..\n";
name = original.name;
color = original.color;
mileage = new int; // yeh line likhne se , new memory allocate hogi
*mileage = *original.mileage; // memory address copied from previous memory of mileage
}
// 12 and 12 because * and * pointer laga hai this is diff. between shallow n deep copy, to revise watch again for concept clarity..
};
int main() {
Car c1("maruti 800", "white");
Car c2(c1);
cout << c2.name << endl;
cout << c2.color << endl;
cout << *c2.mileage << endl;
*c2.mileage = 10; // changed to 10 (my mistake : remember to use * )
cout << *c1.mileage << endl; // 10
return 0;
}
No comments:
Post a Comment