Pattern 23 | Enforcing 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 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.