FAQ 24.11 What should a derived class do if a base class s assignment operator is virtual ?

FAQ 24.11 What should a derived class do if a base class's assignment operator is virtual?

The developer should probably override the base class's assignment operator and also provide an overloaded assignment operator. For example, when base class B declares B::operator= (const B&) to be virtual, a publicly derived class D should provide both the override (D::operator= (const B&)) and the overload (D:: operator= (const D&)).

 #include <iostream> using namespace std; class B { public:   virtual ~B() throw();   virtual B& operator= (const B& b) throw(); }; B::~B() throw() { } B& B::operator= (const B& b) throw() { cout << "B::operator=(const B&)\n"; return *this; } class D : public B { public:   virtual D& operator= (const B& b) throw();  // override   D& operator= (const D& d) throw();          // overload }; D& D::operator= (const B& b) throw()  // override { cout << "D::operator=(const B&)\n"; return *this; } D& D::operator= (const D& d) throw()  // overload { cout << "D::operator=(const D&)\n"; return *this; } 

Because the compiler resolves which override to call based on the static type of the parameters, the first assignment in the following example is the only one that calls the assignment operator that takes a D; all the others end up calling the assignment operator that takes a B. Because b in sample() is actually of class D, and because the base class's assignment operator is virtual, all four assignments call one of the assignment operators from the derived class.

 void sample(D& d, B& b, D& d2, B& b2) throw() {   cout << "d = d2:  ";  d = d2;   cout << "d = b2:  ";  d = b2;   cout << "b = b2:  ";  b = b2;   cout << "b = d2:  ";  b = d2; } int main() {   D d, b, d2, b2;   sample(d, b, d2, b2); } 

The output is

 d = d2:  D::operator=(const D&) d = b2:  D::operator=(const B&) b = b2:  D::operator=(const B&) b = d2:  D::operator=(const B&) 

The last two calls resolve to the override (D::operator= (const B&)) because the actual class of b in sample()is D. If b had actually been a B, the last two calls would have resolved to B::operator= (const B&). Naturally, these calls could also resolve to some other override if the object's actual class had been some other derived class that provided an override.

Note that D::operator= (const B& b) does not detect that its parameter b is of class D.



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