When you initialize another newly constructed object with a custom class type Object that has already been initialized, the copy constructor is automatically called. In other words, the copy constructor is called when the object of the class needs to be Copied. the copy constructor is called in the following cases:
(1) An object is passed into the function body in the way of value passing
(2) An object is returned from the function in the way that the value is passed
(3) an object needs to be initialized by another object.
If a copy constructor is not explicitly declared in the class, the compiler will automatically generate a default copy constructor that completes the bit copy between the Objects. A bit copy is also called a shallow copy, which is explained Later.
Custom copy constructors are a good programming style that prevents the compiler from forming a default copy constructor, which improves the efficiency of the source Code.
Shallow copy and deep copy
In some cases, In-class member variables need to dynamically open up heap memory, If a bit copy is implemented, that is, the value of the object is completely copied to another object, such as A=b. At this point, if a member variable pointer in B has already applied for memory, that member variable in a also points to the same piece of memory. There is a problem: when B releases the memory (for example, a destructor), A pointer inside a is a wild pointer, and a run error Occurs.
Deep copy and shallow copy can be simply understood As: if a class has resources, when the object of this class has a replication process, the resource is redistributed, the process is a deep copy, conversely, no redistribution of resources, is a shallow copy. Here is an example of a deep copy.