Shallow Copy in c++

#include<iostream>

using namespace std;

class student


public:

string *name;

student(string n)

name= new string(n);

}

student(student &s)

name=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:

​Aapne is code mein ye seekha ke:

​Shared Address: s1 aur s2 dono ke paas aik hi memory address hai.

​Unintended Change: Line *s2.name = "Xyz"; ne us memory box ke andar ka data badal diya.

​The Result: Jab s1 ne apna naam dikhaya, to wo bhi badal chuka tha kyunki wo usi box ko point kar raha tha.

No comments