User defined copy constructor - Features,Definition,Function

Q.  Why is user defined copy constructor required?
- Published on 19 Oct 15

a. there is no implicit copy constructor in C++
b. when pointers are involved implicit copy constructor does not give correct result
c. both a and b
d. none

ANSWER: when pointers are involved implicit copy constructor does not give correct result
 
C++ has an implicit copy constructor which is called by compiler to keep a copy of the object. In case where pointers are present in the code and programmer is not using user defined copy constructor then a problem occurs. The problem is that whenever a copy constructor is called( implicit or user defined) the copy destructor is also called to delete the copy at the end of scope. Implicit copy constructor copies an object bit by bit so pointer address will be copied causing in two different objects sharing same memory location. When the first object calls the destructor to deallocate the pointer no problem occurs but when second object does so it tries to deallocate a pointer that does not exist anymore and the application stops working. In order to prevent situations like this user defined copy constructor is called.

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)