Programming with Passion

Make the best out of everything.

Friday, 8 April 2016

What is 'Copy Constructor' and when it is called?

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.

  1. class SampleClass{
  2. public:
  3. int* ptr;
  4. SampleClass();
  5. // Copy constructor declaration
  6. SampleClass(SampleClass &obj);
  7. };
  8.  
  9. SampleClass::SampleClass(){
  10. ptr = new int();
  11. *ptr = 5;
  12. }
  13.  
  14. // Copy constructor definition
  15. SampleClass::SampleClass(SampleClass &obj){
  16. //create a new object for the pointer
  17. ptr = new int();
  18. // Now manually assign the value
  19. *ptr = *(obj.ptr);
  20. cout<<"Copy constructor...\n";
  21. }

No comments:

Post a Comment