Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a copy constructor

I have a question about copy constructors. I see these examples on internet. the first one says without copy constructors if you change something on student2 the same field change also on student1. but on the second examples changes on student2 doesn't affect student1 because of copy constructor. I didn't understand how this happened, what actually copy constructors do here? (sorry for bad english) (thanks for all answers :) )

class MITStudent {
public:
    int studentID;
    char *name;
    MITStudent() {
        studentID = 0;
        name = "";
}

};
   int main() {
      MITStudent student1;
      student1.studentID = 98;
      char n[] = "foo";
      student1.name = n;
      MITStudent student2 = student1;
      student2.name[0] = 'b';
      cout << student1.name; // boo
 }

second one

class MITStudent {
public:
    int studentID;
    char *name;
    MITStudent() {
        studentID = 0;
        name = "";
    }

    MITStudent(MITStudent &o) {
        name = my_strdup(o.name);
        studentID = o.studentID;
    }

};
int main() {
   MITStudent student1;
   student1.studentID = 98;
   char n[] = "foo";
   student1.name = n;
   MITStudent student2 = student1;
   student2.name[0] = 'b';
   cout << student1.name; // foo

}

like image 569
user1559792 Avatar asked Jun 26 '26 10:06

user1559792


1 Answers

Default copy constructors are generated automatically if you don't specify your own.
They just copy all the class'es members by value to the new class.

The problem usually arises when you have pointers as class members.
The default copy constructor will just copy the address that his held by the pointer.
This means that both the original and the copied class now point at the same object.

That's exactly what happens in your example with the char* "string"...

BTW, as a thumb rule.. if you have a class that has pointers as members, create a custom copy constructor.

like image 192
Yochai Timmer Avatar answered Jun 29 '26 00:06

Yochai Timmer