Hi,
I'm able to write a copy constructor for a class which contains pointer as a data member. However, when I have a reference as a data member, the copy constructor does not help, i.e. when I change that member for one object, the change is reflected in another one also.
Please refer to the code below.
class Student {
private:
int roll_no;
char *pname;
int & marks;
public:
Student():marks(a) {
roll_no = 0;
pname = new char[7];
strcpy(pname, "no one");
}
Student(int a, char *p, int &m):marks(m)
{
roll_no = a;
pname = new char [strlen(p) + 1];
strcpy(pname,
}
Student(const Student &ob): marks(ob.marks)
{
cout << "TRACE: in copy con" << endl;
roll_no = ob.roll_no;
pname = new char[strlen(ob.pname)+1];
strcpy(pname, ob.pname);
}
void change_data(int num, char *str, int n)
{
roll_no = num;
strcpy(pname,str);
marks = n;
}
void show_data();
};
int main()
{
int a = 102;
Student Ajay(1, "Ajay",a) ;
Student s1 = Ajay;
Ajay.show_data(); // 1 Ajay 102
s1.show_data(); // 1 Ajay 102
a = 1122;
s1.change_data(12,"Roshan",a);
Ajay.show_data(); // 1 Ajay 1122
s1.show_data(); // 12 Roshan 1122
return 0;
}
now the question is, how to avoid this reflection of values in both the objects?