FAQ 8.17 Does the fact that an array-of Derived can be passed as an array-of Base mean that arrays are bad?
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 }
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. |