A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).
- A variable is declared which is initialized from another object, eg,
Person q("Mickey"); // constructor is used to build q.
Person r(p); // copy constructor is used to build r.
Person p = q; // copy constructor is used to initialize in declaration.
p = q; // Assignment operator, no constructor or copy constructor.
- A value parameter is initialized from its corresponding argument.
f(p); // copy constructor initializes formal value parameter.
- An object is returned by a function.
C++ calls a copy constructor to make a copy of an object in each of the above cases. If there is no copy constructor defined for the class, C++ uses the default copy constructor which copies each field, ie, makes ashallow copy.