FAQ 27.08 What is an alternative to dynamic type checking with containers?

graphics/new_icon.gif

Templates offer a viable alternative when working with containers.

In the past, some container classes were designed assuming the existence of some kind of master base class. This has been called the based object approach. In particular, it was common to encounter container classes that inserted or extracted elements that were pointers to a single base class, typically called Object.

Applying the based object approach to containers makes it hard to mix two or more class libraries. For example, it may not be possible to put an object from one library into a container from another library, since the master base classes from the two libraries normally won't match exactly.

In general, this approach can and should be avoided through the use of templates or design patterns. The particular problem of extensible container classes has been elegantly solved in the standard C++ container classes by using templates and iterators.

Note that Java always inherits all classes from class Object. But since there is exactly one Object class in Java, as opposed to one per library vendor in C++, it isn't as big a problem in Java. The important point is that Java and C++ are very different in some fundamental ways. Syntactically they appear to be quite similar, but semantically there are some fundamental differences. Therefore just because a technique works in one language (say the based object approach works in Java) does not mean the same approach works or should be made to work in a different language (see FAQ 28.08).



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