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); }
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). |