Let's look at the following example:
#include <iostream> using namespace std; class Student { public: int id; char *name; Student() { id = 0; name = ""; } }; int main() { Student student1; student1.id = 10; char nm[] = "Clinton"; student1.name = nm; Student student2 = student1; student2.name[0] = 'P'; cout << student1.name; // Plinton return 0; }
As shown in the example, we made another instance of Student class which is student2 from an existing instance student1. However, later we modified an element of the name array. It turned out that modifying a field of one instance can affect the other instance, and that's not we wanted.
So, to control the assigning operation, we need our own copy constructor not the default copy constructor that compiler provides:
#include <iostream>
using namespace std;
class Student
{
public:
int id;
char *name;
Student()
{
id = 0;
name = "";
}
Student(Student &s)
{
id = s.id;
name = strdup(s.name);
}
};
int main()
{
Student student1;
student1.id = 10;
char nm[] = "Clinton";
student1.name = nm;
Student student2 = student1;
student2.name[0] = 'P';
cout << student1.name << endl; // Clinton
cout << student2.name << endl; // Plinton
return 0;
}
Note that strdup() in our own copy constructor does dynamic memory allocation for the character array including the end character '\0' and returns the address of the heap memory. In other words, the new instance has its own memory to store the name not shared one with which it was instantiated from.
No comments:
Post a Comment