When an object is passed by value, returned by value, or explicitly copied. Here is an example showing all three situations. #include <iostream> using namespace std; class X { public: X() throw(); X(const X&) throw(); }; X::X() throw() { cout << "default constructor\n"; } X::X(const X&) throw() { cout << "copy constructor\n"; } X userCode(X b) throw() <-- 1 { X c = b; <-- 2 return c; } <-- 3 int main() { X a; cout << "calling userCode()\n"; X d = userCode(a); cout << "back in main()\n"; }
The (annotated) output of this program is default constructor <-- 1 calling userCode() copy constructor <-- 2 copy constructor <-- 3 copy constructor <-- 4 back in main()
Note that pass-by-value calls the copy constructor if the caller supplies another object of the same class. Supplying something else may invoke a different constructor. Similar comments apply to return-by-value. |