FAQ 30.05 What happens when an object that doesn t have an explicit assignment operator is assigned?

FAQ 30.05 What happens when an object that doesn't have an explicit assignment operator is assigned?

The compiler synthesizes an assignment operator for the object's class.

For example, if an object of class Fred is assigned and class Fred doesn't provide an explicit assignment operator, the compiler synthesizes an assignment operator that assigns all the Fred object's member objects and base class subobjects. This is called memberwise assignment. Thus if class Fred doesn't have an explicit assignment operator and an object of class Fred contains an object of class Member that has an explicit assignment operator, then the compiler's synthesized Fred::operator= (const Fred&) invokes Member's assignment operator.

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

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

(1) Fred doesn't have an explicit assignment operator

(2) Compiler-synthesized assignment operator Fred::operator= (const Fred&) called here

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

 constructing a Member constructing a Member assigning 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