Translate

Thursday, December 19, 2013

cc++c# What is 'Copy Constructor' and when it is called?

This is a frequent c++ interview question. Copy constructor is a special constructor of a class which is used to create copy of an object. Compiler will give a default copy constructor if you dont define one. This implicit construtor will copy all the members of source object to target object.
Implicit copy constructors are not recommended, because if the source object contains pointers they will be copied to target object, and it may cause heap corruption when both the objects with pointers referring to the same location does an update to the memory location. In this case its better to define a custom copy constructor and do a deep copy of the object.

Example :

‪#‎include‬ <iostream>
using namespace std;

class SampleClass{
public:
int* ptr;
SampleClass();
// Copy constructor declaration
SampleClass(SampleClass &amp;obj);
};

SampleClass::SampleClass(){
ptr = new int();
*ptr = 5;
}

// Copy constructor definition
SampleClass::SampleClass(SampleClass &amp;obj){
//create an new object for the pointer
ptr = new int();
// Now manually assign the value
*ptr = *(obj.ptr);
cout << "Copy constructor...\n";
}