When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference).
When should we write our own copy constructor?
C++ compiler provides default copy constructor (and assignment operator) with class. When we don’t provide an implementation of copy constructor (and assignment operator) and try to initialize an object with the already initialized object of the same class then copy constructor gets called and copies members of class one by one in the target object.
But the problem with the default copy constructor (and assignment operator) is:
- When we have members which dynamically get initialized at run time, the default copy constructor copies this member with the address of dynamically allocated memory and not a real copy of this memory.
- Now, both the objects point to the same memory, and changes in one reflects in another object.
- Further, the main disastrous effect is, when we delete one of these objects another object still points to the same memory, which will be a dangling pointer, and memory leak is also a possible problem with this approach.
So, we need to define our own copy constructor only if an object has pointers or any runtime allocation of the resource like filehandle, a network connection, etc.
The default constructor does only shallow copy.
Deep copy is possible only with a user-defined copy constructor. In a user-defined copy constructor, we make sure that pointers (or references) of copied objects point to new memory locations.
Hence, in such cases, we should always write our own copy constructor (and assignment operator).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...