FAQ 7.05 Is substitutability based on what the code does or what the specification promises the code will do?

The specification, not the implementation.

The specification of an overridden member function must require no more and promise no less than the specification of the corresponding member function in the base class. The overriden member functions must also correctly implement whatever specifications they provide. However, when the base class gives an adaptable specification, the code of the override doesn't necessarily have to do the same as the code of the base class.

In the following example, Base::f() provides an adaptable specification: the code is more specific than the strict minimum guaranteed by the specification. The code of the derived class isn't substitutable with respect to the implementation of the base class, but it is substitutable with respect to the specification of the base class. Since the user code, sample(Base& b), relies only on the specification of Base::f() rather than the more specific implementation, this user code won't break when it is passed a Derived object. However, if the user code had relied on the implementation of Base::f(), it would break when passed a Derived object (it would also break if a legitimate, substitutable modification was made to Base::f(), such as returning 42).

 #include <iostream> using namespace std; class Base { public:   virtual int f();     // PROMISE: Return value will be some even number   virtual ~Base(); }; Base::~Base() { } class Derived : public Base { public:   virtual int f();     // PROMISE: Return value will be 8 }; int Base::f() {   // This is allowed to return any even number   return 4; } int Derived::f() {   // This must return 8...   return 8; } void sample(Base& b) {   int result = b.f();   // This is allowed to expect that result will be even,   // but it must not assume that result is 4   if (result % 2 == 1)     cerr << "PANIC: call the hotline at 1-800-BAD-BUGS\n"; } int main() {   Base b;     sample(b);   Derived d;  sample(d); } 

Never assume that a class will always be implemented as it is currently implemented (see FAQ 6.02).



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