22.12. Runtime class information

When you have an array of polymorphic pointers, how do you tell what kind of class pointer you have? That is, after you set a cCritter* pcritter somewhere in your code, how can you tell if pcritter is just a cCritter* or whether it is perhaps a cCritterBullet* ? (For this discussion, assume that we have a cCritterBullet class that inherits from cCritter.) There are two ways to deal with this.

A hand-made way would be to keep a CString _classname field inside our cCritter class and set it to either cCritter or to cCritterBullet, depending on whether the object was constructed by the cCritter constructor or by the cCritterBullet constructor. And then you could find out if a cCritter * pcritter is really a cCritterBullet ...

Get Software Engineering and Computer Games 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.