A a0;
cout<<"values in a0 before\n";
a0.getval();
A a1(5);
A a2;
A a3=a2;
cout<<"values in a3 after a3=a2 \n";
a3.getval();
cout<<"values in a2 before \n";
a2.getval();
a2.setval("Tom"); // <<<<============Here it does not seg fault.
cout<<"values in a2 after a2 setval \n";
a2.getval();
cout<<"values in a3 after a2 setval \n";
a3.getval();
cout<<"values in a1 before\n";
a1.getval();
a1.setval("Tindol"); // <<<<============But here it seg faults.
cout<<"values in a1 after\n";
a1.getval();
a0=a2=a1;
cout<<"values in a0 after\n";
a0.getval();
A::A(int c):k(7),i(c/2),m(c)m is a reference.
You binds it to temporary variable c.
After end of the constructor it any attempt to write it will overwrite some random memory.
By some chance address of c-stirng you pass in setval is in the exact same area. When you are trying to assign 44 to m, it overwrites pointer value. You can see it for yourself by commention out m=44 in setval.
Solution: never bind references to variables which lifetime is shorter than reference.
Second problem: you are trying to output string contained in name member. But it value is not initialised yet. So attempts to read it lead to undefined behavior. Internally there is probably no null terminator and output operator tries to read until it hit unallocated memory.
In your second comment did you mean to null terminate string after using strcpy ?
or you advice me to use some other string copy function like strncpy ?