The issue with the Copy constructor
I have mentioned a few important concepts in my previous post, it is good to go back and read it before directly jump into this post that talks about the issue of using a copy constructor.
There will be a problem when we use a (shallow) copy constructor to allocate dynamic memory in Heap.
Let us imagine we want to create a character for a game and a character has an integer data member of HP, indicating its health. Once the health value reached 0, the character will die and the game is over. The other data member is a backpack, where the character can put int and withdraw tools. IN our case, we use integer type for simplicity to illustrate the issue of a copy constructor. Consider the following character class.
There are 2 constructors above. One is the parameterized constructor, with input HP parameters. The other one is a copy constructor that copies an object from one to another. Let’s say we created a character c1 and we want to create another character c2 by using the copy constructor. Can you imagine what will goes wrong? Consider the code and result below.
We can see that in the copy constructor, the address of the array we created in the heap is the same for both c1 and c2! This is terrible because when we add or remove tools from the backpack in c1, c2 is also referencing to it, sharing the tools with c1! But what we want is to copy the object entirely into a different new object. What the constructor is doing is called the Shallow Copy. We are just copying the value from object c1 to c2 by value but not by references. In our case, we want to allocate new memory for character c2, Consider the following diagram of what is happening when we do a shallow copy.
Whenever we use a copy constructor, we need to be careful that if there are any dynamic memory allocation in Heap in C++. If that is the case, we need to write our own copy constructor as the default copy constructor in C++ will only perform a shallow copy.
In the deep copy constructor, we allocate new memory blocks in Heap and copy each value from the reference value in the old object to the new object. The following diagram is what we want to achieve.
I have illustrated the issue when we use a copy constructor. There are more to talk about when we overload constructor in C++. I will also cover how to overload operator in C++ later on.