Technical Interview

Home
Technical Interview
Interview Process
Introduction Questions
Quantitative Problems
Google & Microsoft
Algorithms
C/C++ Questions
Java Questions
Data Structures
Fundamental Questions
Puzzles
Resume Tips
Added Recently
Links
Contact Us
Submit Question/Answer

What is the difference between copy constructor & assignment operator?  

Copy constructor is a special type of constructor used in C++ language to create a copy of an object. If we don't explicitly declare one, the compiler creates one by default. This default constructor doesn't do much except for byte-by-byte copy. In special cases, where class owns a pointer or file-descriptor it is not generally recommended to have byte-by-byte copy. In such cases, the developer has to create a constructor customized for the use.

For example, in case Class A has a member which is pointer to an int. If a default copy-constructor is used,
A obj2 = obj1 ;
obj2's member pointer will point to the same memory location is pointed by obj1's pointer. This can later cause problems like memory leak, or dangling pointer.
So in such cases, if the developer writes his own copy-constructor and makes sure that obj2's pointer now points to a different memory location which has the same data value as in obj1's pointer.

A::A (const A&) {
int *ptrMember = new int ;
*ptrMember= *A.ptrMember
}