Item 3: Do not use polymorphism for Arrays
In the language specification, a base class pointer is used to delete an array containing a derived class object, and the result is uncertain.
[Cpp]
01. class BST {...};
02. class BalancedBST: public BST {...};
03.
04. void printBSTArray (ostream & s, const BST array [], int numElements)
05 .{
06. for (int I = 0; I <numElements ;)
07 .{
08. s <array [I]; // assume that the BST class has overloaded the operator <
09 .}
10 .}
Class BST {...};
Class BalancedBST: public BST {...};
Void printBSTArray (ostream & s, const BST array [], int numElements)
{
For (int I = 0; I <numElements ;)
{
S <array [I]; // assume that the operator is overloaded by the BST class <
}
}
The compiler originally assumes that the element in the array is the same as the size of the BST object, but the size of each object in the array is the same as that of the BalancedBST object. The length of a derived class is generally longer than that of a base class. We expect the length of the BalancedBST object to be longer than that of the BST object. In this case, the pointer algorithm generated by the printBSTArray function will be incorrect. No one knows what the consequences will occur if the BalancedBST array is used to execute the printBSTArray function. Whatever the outcome is unpleasant.
It is worth noting that if you do not derive another specific class (such as BalancedBST) from a specific class (concrete classes) (such as BST ), then you are unlikely to make this mistake of using the polymorphism array.