Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Examples

Example: Drawing shapes. The classic example is drawing objects. A typical C-style, switch-on-type solution would define an enumerated member variable id_ for each shape that stores the type of that shape: rectangle, circle, and so on. Drawing code looks up the type and performs specific tasks:

class Shape { // ...
  enum { RECTANGLE, TRIANGLE, CIRCLE } id_;

  void Draw() const {
   switch( id_ ) {                          // bad
   case RECTANGLE:
    // ... rectangle drawing code ...
    break;

   case TRIANGLE:
    // ... triangle drawing code ...
    break;

   case CIRCLE:
    // ... circle drawing code ...
    break;

   default:                                 // bad
    assert( !"Oops, forgot to update this switch when adding a new Shape" );
    break;
   }
  }
};

					  


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint