More efficient C ++ Reading Notes 3

Source: Internet
Author: User

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.


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.