FAQ 24.09 How should the assignment operator in a derived class behave?

An assignment operator in a derived class should call the assignment operator in its direct base classes (to assign those member objects that are declared in the base class), then call the assignment operators of its member objects (to change those member objects that are declared in the derived class). These assignments should normally be in the same order that the base classes and member objects appear in the class's definition. An example follows.

 class Base { public:   Base& operator= (const Base& b) throw(); protected:   int i_; }; Base& Base::operator= (const Base& b) throw() {   i_ = b.i_;   return *this; } class Derived : public Base { public:   Derived& operator= (const Derived& d) throw(); protected:   int j_; }; Derived& Derived::operator= (const Derived& d) throw() {   Base::operator= (d);   j_ = d.j_;   return *this; } 

Typically, a Derived::operator= shouldn't access the member objects defined in a base class; instead it should call its base class's assignment operator. Nor should a Base::operator= access member objects defined in a derived class (that is, it usually shouldn't call a virtual routine, like copyState(), to copy the derived class's state).

If a Base::operator= tried to copy a derived class's state via a virtual function, the compiler-synthesized assignment operators in the derived classes would be invalidated. This requires defining an explicit assignment operator in an unnecessarily large percentage of the derived classes. This added work often negates any common code that is shared in the base class's assignment operator.

For example, suppose Base defines Base::operator= (const Base& b), and this assignment operator calls virtual function copyFrom(const Base&). If the derived class Derived overrides copyFrom(const Base&) to change the entire abstract state of the Derived object, then the compiler-synthesized implementation of Derived::operator= (const Derived&) is likely to be unacceptable: the compiler-synthesized Derived::operator= (const Derived&) would call Base::operator= (const Base&), which would call back to Derived:: copyFrom(const Base&); after returning, the Derived state would be assigned a second time by Derived::operator= (const Derived&).

At best, this is a waste of CPU cycles because it reassigns the Derived member objects. At worst, this is semantically incorrect, because special changes made during Derived::copyFrom(const Base&) may get wiped out when the Derived member objects are subsequently assigned by Derived::operator= (const Derived&).



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