C++
Copy constructor(Deep copy, Shallow copy) in C++
seoca
2018. 11. 9. 07:11
Copy constructor
A copy constructor is a constructor that copies all the information of an object by passing the object as an argument to a function. The compiler defines a default copy constructor if copy constructor is not defined.
Usually, a copy constructor is used for copying objects. For example, in a game, you use it to create multiple monsters.
The basic form of a copy constructor
1 2 3 | classname (const classname &obj) { //body } | cs |
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Bank { private: int num; int cnum; public: Bank() { //constructor num = 0; cnum = 0; } ~Bank() { cout << "destructor" << endl; //destructor } Bank(const Bank& bank) { //copy constructor cout << "copy constructor called" << endl; this->num = bank.num; this->cnum = bank.cnum; } }; int main() { Bank bank; int a = 20; int b = 30; cout << a << b << endl; Bank bank2 = bank; return 0; } | cs |
Result
Shallow copy and Deep copy
It is a shallow copy that only the reference is copied. Unlike a shallow copy, deep copy creates a new copy of a referred object.
Shallow copy example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | class Bank { private: int *num; int arrNum; public: Bank(const Bank &pBank) { num = pBank.num; // Shallow copy occurred } Bank(void) { cout << "Enter a number: "; cin >> arrNum; cout << "the number of elements is: " << arrNum << endl; num = new int[arrNum]; for (int i = 0; i < arrNum; i++) { cout << "Enter the numbers: " << i + 1 << ":"; cin >> num[i]; } for (int j = 0; j < arrNum; j++) { cout << num[j] << " , " << endl; } } ~Bank(void) { cout << endl; cout << "Destructor" << endl; delete[] num; //Error occurred when it executes. // bank2 can not executed because bank1 has already deleted } }; int main(void) { Bank bank1; Bank bank2 = bank1; return 0; } | cs |
Deep copy example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Bank { private: int *num; int arrNum; public: Bank(const Bank &pBank) { num = new int[arrNum]; //Deep copy occurred } Bank(void) { cout << "Enter a number: "; cin >> arrNum; cout << "the number of elements is: " << arrNum << endl; num = new int[arrNum]; for (int i = 0; i < arrNum; i++) { cout << "Enter the numbers: " << i + 1 << ":"; cin >> num[i]; } for (int j = 0; j < arrNum; j++) { cout << num[j] << " , " << endl; } } ~Bank(void) { cout << endl; cout << "Destructor" << endl; delete[] num; } }; int main(void) { Bank bank1; Bank bank2 = bank1; return 0; } | cs |
Result