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).
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Copy Constructor in C++
- When is copy constructor called?
- Why copy constructor argument should be const in C++?
- Advanced C++ | Virtual Copy Constructor
- Copy constructor vs assignment operator in C++
- Does C++ compiler create default constructor when we write our own?
- Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backwards()
- Constructor Overloading in C++
- Can a constructor be private in C++ ?
- Constructor Delegation in C++
- What is conversion constructor in C++?
- Dynamic Constructor in C++ with Examples
- Difference Between Constructor and Destructor in C++
- Passing a vector to constructor in C++
- How to create a List with Constructor in C++ STL
Improved By : HridaynathPawar