FAQ 30.04 What happens if an object is copied but doesn t have an explicit copy constructor?

FAQ 30.04 What happens if an object is copied but doesn't have an explicit copy constructor?

The compiler synthesizes a copy constructor for the object's class.

For example, if an object of class Fred is copied and class Fred doesn't provide an explicit copy constructor, the compiler synthesizes a copy constructor that copy constructs all the Fred object's member objects and base class subobjects. This is called memberwise copy construction. Thus, if class Fred doesn't have an explicit copy constructor, and an object of class Fred contains an object of class Member that has an explicit copy constructor, then the compiler's synthesized Fred::Fred(const Fred&) invokes Member's copy constructor.

Built-in types (int, float, void*, and so on) can be viewed as having copy constructors that do a bitwise copy.

 #include <iostream> using namespace std; class Member { public:   Member() throw();   Member(const Member&) throw(); }; Member::Member() throw() { cout << "constructing a Member\n"; } Member::Member(const Member&) throw() { cout << "copying a Member\n"; } class Fred { public:   Fred() throw();                                                      <-- 1 protected:   Member member_; }; Fred::Fred() throw() : member_() { } int main() {   Fred a;   Fred b = a;                                        <-- 2 } 

(1) Fred doesn't have an explicit copy constructor

(2) Compiler-synthesized copy constructor Fred::Fred(const Fred&) called here

The compiler's synthesized Fred::Fred(const Fred&) calls Member:: Member(const Member&) automatically, so the output is

 constructing a Member copying a Member 


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