FAQ 7.01 What is proper inheritance?

When the advertised behavior of the derived class is substitutable for that of the base class.

Proper inheritance and substitutable behavior can be guaranteed when the specifications of the member functions of the derived class require no more and promise no less than the specifications of the corresponding member functions in the base class(es). The derived class can also add new member functions. The specification for these new member functions can require as much or promise as little as they like, since they are not constrained by existing member functions in any base class.

In the following example, the specification for Derived::f() requires no more (in fact, it imposes a weaker requirement) and promises no less (in fact, it makes a stronger promise) than the specification of Base::f(). This will not break users of the base class, so this is proper inheritance.

 #include <iostream> using namespace std; class Base { public:   virtual int f(int x);     // REQUIRE: Parameter x must be an odd number     // PROMISE: Return value will be some even number   virtual ~Base(); }; Base::~Base() { } class Derived : public Base { public:   virtual int f(int x);     // REQUIRE: Parameter x can be any integer     // PROMISE: Return value will be 8 }; int Base::f(int x) {   if (x % 2 == 0)     throw "Even!";   return x + 1; } int Derived::f(int x) { return 8; } void sample(Base& b) {   // We should pass only odd numbers, since b may actually   // be a Base...   int result = b.f(37);   // We expect result to be even   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); } 

Note that every member function of the derived class must have substitutable behavior with respect to the corresponding specification in the base class(es). If even one derived class member function specifies stronger requirements or weaker promises than the corresponding specification in the appropriate base class, the inheritance relationship is improper.

Finally note that this chapter deals with public inheritance. private and protected inheritance have completely different rules (see FAQ 37.01).



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