Pattern 23Enforcing Polymorphic Type Safety

Purpose

This pattern detects type incompatibilities in object pointer assignments in object-oriented languages like C++.

Discussion

Beyond the type checking done in Pattern 22, Enforcing Static Type Safety, object-oriented languages have one more type hazard to worry about: polymorphic object pointer assignment. Polymorphism means that a pointer can refer to objects of multiple types. In contrast, C pointer assignments have to be between exact types. The key difference then between this pattern and the previous lies in the definition of type compatibility. Let’s take a look at a C++ example that demonstrates what we need to handle:

 
Cat *pCat;
 
Bengal *pBengal; ​// assume Bengal subclasses Cat
 

Get Language Implementation Patterns now with O’Reilly online learning.

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