Copy constructor

This tip submitted by Ali Nawkhas Murad on 2012-01-30 04:29:02. It has been viewed 19917 times.
Rating of 5.3 with 167 votes

For some reason or another you may need to save complete copy of object when it reaches at some moment of times, for using it in future. So you can instantiate new object with copy constructor. Useful for data structure (stack, queue, tree, �etc). A copy constructor is a constructor that takes a parameter that is the same type as the class itself:

class CopiableClass
   CopiableClass (const CopiableClass& other); // copy constructor

The copy constructor should invoke the parent class copy constructor and the copy constructor for all fields. If your class has pointers, it should generally allocate new pointers using the constructors for each pointer type, or if the pointer is a polymorphic type, you should use a polymorphic copy method such as clone.

More tips

Help your fellow programmers! Add a tip!