Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we have to use copy constructors?

I know that C++ compiler creates a copy constructor for a class. In which case do we have to write a user-defined copy constructor? Can you give some examples?

like image 538
penguru Avatar asked Jul 19 '10 05:07

penguru


People also ask

Why do we need a copy constructor?

Copy constructor is used to initialize the members of a newly created object by copying the members of an already existing object. Copy constructor takes a reference to an object of the same class as an argument.

Why and when do you need copy constructors Is there any situation where you want to only implement a copy constructor or an assignment operator but not both?

Copy Constructor is called when an object is either passed by value, returned by value, or explicitly copied. If there is no copy constructor, c++ creates a default copy constructor which makes a shallow copy. If the object has no pointers to dynamically allocated memory then shallow copy will do.

Why do we need copy constructor in Java?

A copy constructor in a Java class is a constructor that creates an object using another object of the same Java class. That's helpful when we want to copy a complex object that has several fields, or when we want to make a deep copy of an existing object.


1 Answers

The copy constructor generated by the compiler does member-wise copying. Sometimes that is not sufficient. For example:

class Class { public:     Class( const char* str );     ~Class(); private:     char* stored; };  Class::Class( const char* str ) {     stored = new char[srtlen( str ) + 1 ];     strcpy( stored, str ); }  Class::~Class() {     delete[] stored; } 

in this case member-wise copying of stored member will not duplicate the buffer (only the pointer will be copied), so the first to be destroyed copy sharing the buffer will call delete[] successfully and the second will run into undefined behavior. You need deep copying copy constructor (and assignment operator as well).

Class::Class( const Class& another ) {     stored = new char[strlen(another.stored) + 1];     strcpy( stored, another.stored ); }  void Class::operator = ( const Class& another ) {     char* temp = new char[strlen(another.stored) + 1];     strcpy( temp, another.stored);     delete[] stored;     stored = temp; } 
like image 103
sharptooth Avatar answered Oct 28 '22 23:10

sharptooth