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 }
The compiler's synthesized Fred::Fred(const Fred&) calls Member:: Member(const Member&) automatically, so the output is constructing a Member copying a Member |