Skip to content
Related Articles

Related Articles

When should we write our own copy constructor?
  • Difficulty Level : Easy
  • Last Updated : 19 Sep, 2018
GeeksforGeeks - Summer Carnival Banner

C++ compiler provide default copy constructor (and assignment operator) with class. When we don’t provide implementation of copy constructor (and assignment operator) and tries to initialize object with already initialized object of same class then copy constructor gets called and copies members of class one by one in target object.

The problem with default copy constructor (and assignment operator) is – When we have members which dynamically gets initialized at run time, default copy constructor copies this members with address of dynamically allocated memory and not real copy of this memory. Now both the objects points to the same memory and changes in one reflects in another object, Further the main disastrous effect is, when we delete one of this object other object still points to same memory, which will be dangling pointer, and memory leak is also possible problem with this approach.

Hense, in such cases, we should always write our own copy constructor (and assignment operator).

Source: http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :