FAQ 8.17 Does the fact that an array-of Derived can be passed as an array-of Base mean that arrays are bad?

FAQ 8.17 Does the fact that an array-of Derived can be passed as an array-of Base mean that arrays are bad?

graphics/new_icon.gif

Yes, arrays are dangerous. Use template container classes instead.

Compared to a C++ array, a template container class (see FAQs 2.15, 28.01) catches more errors at compile time, thus reducing the reliance on runtime testing. For example, if the standard template vector<T> had been used, the previous attempt to pass a vector<Derived> as a vector<Base> would have been caught at compile time.

 #include <vector> #include <iostream> using namespace std; void sample(vector<Base>& a) throw() {   cout << "a[0].f(): ";   a[0].f();   cout << "a[1].f(): ";   a[1].f(); } int main() {   vector<Base> b(10);   sample(b);   #ifdef GENERATE_ERROR     vector<Derived> d(10);     sample(d);                                       <-- 1   #endif } 

(1) Error caught at compile time (fortunately)

Templates allow the compiler to distinguish between a pointer to a thing and a reference to an array-of things. In contrast, when C++ arrays were used in the previous FAQ, the compiler wasn't able to detect the error of passing an array-of Derived as if it were a kind-of array-of Base. The compiler detects this error if templates are used.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net