#include<bits/stdc++.h>
using namespace std;
class student{
public:
int age;
string name;
student(){
age = 0;
name = "";
}
void setName(string name){
this->name = name;
}
void setAge(int age){
this->age = age;
}
void print(){
cout<<"Name is: "<<this->name<<" ";
cout<<"Age is: "<<this->age<<endl;
}
};
int main(){
student s1;
s1.setAge(20);
s1.setName("Ajay");
student s2(s1);
s1.print();
cout<<endl;
s2.print();
cout<<endl;
s1.name[0]='B';
s1.print();
cout<<endl;
s2.print();
cout<<endl;
}
Output:
Name is: Ajay Age is: 20
Name is: Ajay Age is: 20
Name is: Bjay Age is: 20
Name is: Ajay Age is: 20
As per the shallow copy concept the name of second student should also change( to = "Bjay") since they both share the same memory, but the changes are not being reflected
Why is it so? Don't the both objects share the same memory.