TITLE: why use templates over inheritance PROBLEM: Andy As a relative newcomer to C++(very relative) but an experienced OO programmer I'm having some problems seeing the place of Templates over the use of Polymorphism and inheritance. It seems that templates do nothing extra (except efficiency ?) that could not be achieved using inheritance, and it seems that inheritance is a more elegant approach? Am I completely missing the point? Any explanations would be warmly received. RESPONSE: bs@research.att.com (Bjarne Stroustrup), 6 Mar 96 Efficiency is one part of the answer (and that can be a big deal), and type safety is another. Consider containers. Here is a simple list (for simplicity, I deal with pointers only here): template class list { public: T* get(); // remove and return current element void put(T*); // put before current element // ... }; which can be used to write a function that rotates shapes: void f(list* p) { while (shape* s = p->get()) s->draw(); } Since the list is declared as a list of shapes, only shapes can be on it. This style of list in non-intrusive; that is, it doesn't require any restrictions on the layout of objects put on the list. Consider another style: class List { public: Object* get(); // remove and return current element void put(Object*); // put before current element // ... }; which can again be used to write a function that rotates shapes: void f2(List* p) { while (Object* oo = p->get()) { if (shape* s = dynamic_cast(oo)) s->draw(); else { // oops! do something else } } } It is necessary to test whether the objects coming off the list really are shapes because objects of any class derived from class object can be put on the list. To be on List, an object must be derived from Object. In particular, built-in types and types with layout constraints cannot be directly put on such lists (the way they can for the template-style list). I consider the code using templates the cleaner by far. In C++, templates can be used to provide a type-safe interface for containers based on a "universal" base type. In other languages, syntactic sugar can hide the run-time check, but not the time and space overheads. Both styles have been used in many successful systems; container class design is a multi-facetted and interesting topic. However, for a language such as C++, I think the template style is fundamentally cleaner. The C++ standard library provides a variant of the template approach. - Bjarne PS Note that the non-template style is actually a special case of the template case. Given the list template might define List like this: class List : public list { };