FAQ 8.15 Is parking-lot-for-cars a kind-of parking-lot-for-arbitrary-vehicles (assuming parking-lot-for-vehicles allows parking any kind-of vehicle)?

graphics/new_icon.gif

NO!

This is another specific example of the general guideline presented earlier.

In the following, Vehicle is an ABC and Car and NuclearSubmarine are concrete kinds-of Vehicle.

graphics/08fig03.gif

 #include <iostream> using namespace std; class Vehicle { public:   virtual ~Vehicle(); }; Vehicle::~Vehicle() { } class Car : public Vehicle { public:   virtual void startEngine() throw(); }; void Car::startEngine() throw() { cout << "starting a Car...\n"; } class NuclearSubmarine : public Vehicle { public:   virtual void launchMissile(); }; void NuclearSubmarine::launchMissile() throw() { cout << "starting a War...\n"; } 

If a container of Car was a kind-of container of Vehicle, someone might put a NuclearSubmarine inside the container of Car, then remove the NuclearSubmarine thinking it was a Car.

This is an egregious error. When the startEngine() member function is called, the launchMissile() may actually be executed (depending on the compiler and implementation). Thus, starting the car's engine might inadvertently start World War III! See the previous FAQ to see the user code that might cause this to happen.

The root problem is bad inheritance. A bad design can't be patched with a little extra inheritance. Throwing more inheritance at an already defective design will usually make it worse. If the design is broken, it needs to be fixed, not patched with clever coding tricks.



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