Deep Copy in c++

 #include<iostream>

using namespace std;

class student


public:

string *name;

student(string n)

name=new string(n);

}

student(student &s)

name=new string(*s.name);


}

void display()


cout<<"Name of Student is : "<<*name<<endl;

}

};

int main()


student s1("Abc");

student s2=s1;

cout<<"Output is :"<<endl;

s1.display();

s2.display();

*s2.name="Xyz";

cout<<" After modification"<<endl;

s1.display();

s2.display();

}

Explanation

​New Memory Allocation: name = new string(*s.name); wali line ne memory mein aik naya dabba banaya.

​Data Independence: Jab aapne s2.name ko "Xyz" kiya, to sirf s2 ki memory update hui. s1 ki memory mein ab bhi "Abc" mehfooz hai.

​Result: Output mein s1 ka naam tabdeel nahi hoga.


No comments