« Copy Constructor

Inbuilt copy constructor uses shallow copy

if we have written our own copy constructor then inbuilt copy constructor won't be available to us.

1char name[] = "abcd";
2Student s8(20, name);
3cout << "s8: " << endl;
4s8.display();
5
6name[3] = 'e';
7Student s9(24, name);
8cout << "s9: " << endl;
9s9.display();
10cout << "s8: " << endl;
11s8.display();
12
13Student s21(s8);
14cout << "s21: " << endl;
15s21.display();
16s8.name[2] = 'm';
17cout << "s21: " << endl;
18s21.display();

inbuilt_copy_constructor.jpg

Writing our own copy constructor to perform deep copy

1Student(Student const &s)
2{
3 this->age = s.age;
4 // this->name = s.name; shallow copy
5 this->rollNumber = s.rollNumber;
6 this->name = new char[strlen(s.name) + 1];
7 strcpy(this->name, s.name);
8}

inflinite_loop.jpg

For full github code use:

https://github.com/anishakd4/ds/tree/master/cn/oops