class Student {
private:
int age;
public:
char *name;
Student(int age,char*name) {
this->age=age;
this->name=new char[strlen(name)+1];
strcpy(this->name,name);
}
Student(Student const &s1) {
this->age=s1.age;
this->name=new char[strlen(s1.name)+1];
strcpy(this->name,s1.name);
s1.name[0]='x';
}
void display() {
cout<<age<<" "<<name<<endl;
}
};
int main() {
char name[]="abcd";
Student s1(10,name);
s1.display();
Student s2(s1);
s2.name[0]='x';
s1.display();
s2.display();
}
I have passed s1 as a constant reference but I am able to change s1.name[0] and the program compiles successfully. Why I am able to change s1.name[0]?enter image description here
You did not modify s1
. You modified some unrelated memory block (allocated by new
) , to which s1
holds a pointer. In C++ there is no special relationship between a raw pointer and any memory block it might happen to be pointing to.
If you use std::string
instead of raw pointers and manual memory management then this problem will not arise.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments