100. Don’t treat arrays polymorphically

Summary

Arrays are ill-adjusted: Treating arrays polymorphically is a gross type error that your compiler will probably remain silent about. Don’t fall into the trap.

Discussion

Pointers serve two purposes at the same time: that of monikers (small identifiers of objects), and that of array iterators (they can walk through arrays of objects using pointer arithmetic). As monikers, it makes a lot of sense to treat a pointer to Derived as a pointer to Base. As soon as the array iteration part enters the stage, however, such substitutability breaks down because an array of Derived isn’t the same as an array of Base. To illustrate: Mice and elephants are both mammals, but that doesn’t mean a convoy of a thousand ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices 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.