Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

When Should We Write Our Own Copy Constructor in C++?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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. 

Shallow Copy C++

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.  

Deep Copy C++

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. 

My Personal Notes arrow_drop_up
Last Updated : 04 Jan, 2022
Like Article
Save Article
Similar Reads