Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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 a default copy constructor (and assignment operator) with class. When we don’t provide an implementation of the copy constructor (and assignment operator) and try to initialize an object with the already initialized object of the same class then the copy constructor gets called and copies members of the class one by one in the target object. 

But the problem with the default copy constructor (and assignment operator) is: 

  • When we have members that 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 reflect in another object.
  • Further, the main disastrous effect is, that 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 a file handle, a network connection, etc.

Another use case of a copy constructor is when we want to copy only specific data members of the class from one object to another object and keep the remaining data members identical for each object, we can write our own copy constructor.

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).

 


Last Updated : 06 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads