Open In App

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 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: 

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. 

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

 

Article Tags :