⟩ Explain 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 don't define one. This implicit constructor 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.
class SampleClass{
public:
int* ptr;
SampleClass();
// Copy constructor declaration
SampleClass(SampleClass &obj);
};
SampleClass::SampleClass(){
ptr = new int();
*ptr = 5;
}
// Copy constructor definition
SampleClass::SampleClass(SampleClass &obj){
//create a new object for the pointer
ptr = new int();
// Now manually assign the value
*ptr = *(obj.ptr);
cout<<"Copy constructor...n";
}