Saturday 23 June 2012

When are copy constructors called?

A copy constructor is called whenever a new variable is created from an object. This happens in the following cases (but not in assignment).

1) when a function returns an object of that class by value (An object is returned by a function)
2) when the object of that class is passed by value as an argument to a function; A value parameter is initialized from its corresponding argument.
f(p); // copy constructor initializes formal value parameter.
3) when you construct an object based on another object of the same class (Circle c1=c2;)
A variable is declared and 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

4) When an object is thrown
5) When an object is caught
6) When an object is placed in a brace-enclosed initializer list
7) When compiler generates a temporary object

No comments:

Post a Comment