Explain what is 'Copy Constructor' and when it is called?
Submitted by: MuhammadThis 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";
}
Submitted by: Muhammad
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";
}
Submitted by: Muhammad
Read Online C++ Programmer Job Interview Questions And Answers
Top C++ Programmer Questions
☺ | Explain me what is an Object/Instance? |
☺ | Explain void free (void* ptr)? |
☺ | Tell me how to create a pure virtual function? |
☺ | Tell me what will the line of code below print out and why? |
☺ | Please explain is there a difference between class and struct? |
Top C Plus Plus Language Categories
☺ | C++ Pointers & Functions Interview Questions. |
☺ | C++ Operator Overloading Interview Questions. |
☺ | C++ Exception Handling Interview Questions. |
☺ | C++ Template Interview Questions. |
☺ | C++ Virtual Functions Interview Questions. |