FAQ 27.06 Are there better alternatives to dynamic type checking?

One alternative to dynamic type checking and down casts is dynamic binding and virtual functions. To use this alternative technique, member functions that show up only in the derived classes are generalized and moved up to the base class. Effectively this means that the class selection and down cast is performed automatically and safely by C++. Furthermore, this approach produces extensible software because it automatically extends itself whenever a new derived class is created as if an extra case or else if magically appeared in the dynamic type-checking technique.

The following example is a rework of the code from FAQ 27.03. Compared to the old class hierarchy, the italicsXXX() member functions from the derived classes are generalized and moved into the base class as virtual member function italics(). This results in a substantial simplification of the user code printUsingItalics(). Instead of selecting the printer type based on a type() member function and using control flow logic to figure out what to do, the user code simply invokes the new italics() member function.

 class Printer { public:   virtual ~Printer() throw();   virtual void italics(const char* s) throw() = 0; }; Printer::~Printer() throw() { } class EpsonPrinter : public Printer { public:   virtual void italics(const char* s) throw(); }; void EpsonPrinter::italics(const char* s) throw() { cout << esc << "i+" << s << esc << "i-"; } class ProprinterPrinter : public Printer { public:   virtual void italics(const char* s) throw(); }; void ProprinterPrinter::italics(const char* s) throw() { cout << esc << "[i" << s << esc << "[n"; } class StarPrinter : public Printer { public:   virtual void italics(const char* s) throw(); }; void StarPrinter::italics(const char* s) throw() { cout << esc << "x" << s << esc << "y"; } void printUsingItalics(Printer& p, const char* s) throw() { p.italics(s); } 

From a broader standpoint, complexity is moved from the user code to the server code, from the many to the few. This is normally the right trade-off. Furthermore, adding a new kind of Printer doesn't require existing code to be modified reducing the ripple effect when compared to FAQ 27.03.



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