FAQ 20.07 When is a copy constructor invoked?

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"; } 

(1) Pass by value: Copy main()'s a to b

(2) Explicit copy: Copy from b to c

(3) Return by value: Copy from c to main()'s d

The (annotated) output of this program is

 default constructor                                  <-- 1 calling userCode() copy constructor                                     <-- 2 copy constructor                                     <-- 3 copy constructor                                     <-- 4 back in main() 

(1) main()'s a

(2) userCode()'s b

(3) userCode()'s c

(4) main()'s d

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.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net