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).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Does C++ compiler create default constructor when we write our own?
- When should we write our own assignment operator in C++?
- Why copy constructor argument should be const in C++?
- How to implement our own Vector Class in C++?
- Write your own memcpy() and memmove()
- Write your own strlen() for a long string padded with '\0's
- How to write your own header file in C?
- Copy constructor vs assignment operator in C++
- When is copy constructor called?
- Advanced C++ | Virtual Copy Constructor
- Copy Constructor in C++
- Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
- Implement Your Own sizeof
- Implement your own itoa()
- Implement your own tail (Read last n lines of a huge file)
- Implementing own Hash Table with Open Addressing Linear Probing in C++
- Making your own Linux Shell in C
- What is conversion constructor in C++?
- C++ default constructor | Built-in types
- Advanced C++ | Virtual Constructor
Improved By : HridaynathPawar