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, ...

Get Essential C++ now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.