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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.