In C++, the copy constructor for a class X is the constructor member function X::X(const X& x). Its job is to create a copy of the object x passed in. Copying is performed when passing objects by value.

Note that the argument of the copy constructor must be passed by reference. The copy constructor is a function; if its argument were passed by value, the compiler would have to call the copy constructor to pass the copy constructor's argument, which would have to call the copy constructor, etc.

For simple objects the default copy constructor supplied by the compiler is good enough. Some authorities recommend writing a copy constructor in any case, but Bjarne Stroustrup recommends against doing so. The copy constructor may be used to implement various kinds of data sharing -- or to prevent Bad Things from happening because of any sharing induced by the default copy constructor.

If you find yourself in need of a copy constructor, remember the rule of three!

Copy constructor (noun) - the member function called automatically to create a new object that is a copy of an object whose copy constructor is called.

Alright, for everyone who is not me, I apologize and will clean up that sentence a bit. (Disclaimer: all information contained in this writeup is the way things work in C++, so if your favorite Object Oriented language does it differently, it is not my concern right now). When an object is copied, its copy constructor is called. This happens when you pass an object by VALUE. In pass by reference, a reference (or pointer) to the object is passed to the function, so no new objects are created on the run-time heap.

The default copy constructor for an object performs a shallow copy of all data members into the new object. This is fine if your class contains simple integers for example. But, if your class contains pointers, only the address of the pointers is copied to the new object. The most common use for a copy constructor is to perform a deep copy. A deep copy is when you manually create new instances of all the anonymous heap variables your class uses.

Log in or register to write something here or to contact authors.