#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..
~Car() {
cout << "deleting object..\n";
// **destructor - to deallocate memory of mileage.. this frees the memory from heap
if(mileage != NULL)
{
delete mileage;
mileage = NULL;
}
}
};
int main() {
Car c1("maruti 800", "white");
cout << c1.name << endl;
cout << c1.color << endl;
cout << *c1.mileage << endl;
return 0;
}
No comments:
Post a Comment