O'Reilly logo

Essential C++ by Stanley B. Lippman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.10. Run-Time Type Identification

Our implementation of what_am_i() has each class providing a virtual instance that returns a string literal identifying the class:

class Fibonacci : public num_sequence { 
public: 
   virtual const char* what_am_i() const { return "Fibonacci"; } 
   // ... 
}; 

An alternative design is to provide a single num_sequence instance of what_am_i() that each derived class reuses through inheritance. This design frees each derived class from having to provide its own instance of what_am_i().

One way to implement this might be to add a string member to num_sequence. Each derived class constructor would then pass its class name as an argument to the num_sequence constructor. For example,

 inline Fibonacci:: Fibonacci( int len, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required