C++ Programmer Question:

Download Job Interview Questions and Answers PDF

Explain what is 'Copy Constructor' and when it is called?

C++ Programmer Interview Question
C++ Programmer Interview Question

Answer:

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";
}

Download C++ Programmer Interview Questions And Answers PDF

Previous QuestionNext Question
Tell us why pure virtual functions are used if they don't have implementation / When does a pure virtual function become useful?Tell me what are C++ inline functions?