liveBook · Manning

Derived class array

As explained in 100 C++ Mistakes and How to Avoid Them

A derived class array is an array whose elements have a class type derived from another class and whose layout may be larger than the base class layout.

Mistake: treating an array of derived objects as an array of base objects. A derived pointer can replace a base pointer, but array indexing uses the declared element size. Because derived objects may be larger, pointer arithmetic reaches the wrong locations. section 8.10

A cast that appears to work

With B and D, printArray(const B a[]) accepts both B* and D*. Printing the D array produces 0, 1, 0, 1 instead of four consistent derived elements. Passing the same pointer to deleteArray is also unsafe: destruction reports only B objects, not D objects. The apparent polymorphism hides an array-layout error.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains array indexing and destruction consequences, then demonstrates templated functions that preserve the actual element type.
Examples
Uses B and D arrays, printArray and deleteArray, contrasting incorrect and templated implementations with destructor output.
What it assumes
Assumes basic classes, inheritance, pointers, arrays, dynamic allocation, and destructor calls.
What you can do after
Evaluate whether array-based polymorphism is valid and apply type-preserving functions to separate base and derived arrays.
How it connects
Connects inheritance, polymorphism, the Liskov substitution principle, pointer arithmetic, and object destruction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.