FAQ 24.05 How should the assignment operator be declared in an ABC?

The assignment operator of an ABC should generally be protected:.

By default, assignment operators for all classes are public:. For ABCs, this default should usually be changed to protected: so that attempts to assign incompatible objects are trapped as compile-time errors. An example follows.

 class Position { };                                  <-- 1 class Shape { public:   // ... protected:   Position p_; }; class Square : public Shape { /*...*/ }; class Circle : public Shape { /*...*/ }; void sample(Shape& a, Shape& b) { a = b; }                                           <-- 2 int main() {   Square a;   Circle b;   sample(a, b); } 

(1) The position of the Shape

(2) Nonsensical, but (unfortunately) legal since Shape::operator=() is public:

Instead, the assignment operator for an ABC should be protected:, as shown in the following code.

 class Shape { public:   // ... protected:   void operator= (const Shape& s) throw();   Position p_; }; inline void Shape::operator= (const Shape& s) throw() { p_ = s.p_; } 

Note that the protected: assignment operator assigns the internal state of one Shape to another Shape. If it didn't assign the Shape's p_ member object, each derived class would have to define an explicit assignment operator in order to do what the base class's assignment operator should have done in the first place.

Also note that the protected: assignment operator can return void instead of the usual *this (see FAQ 24.07).



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