FAQ 28.08 Can a Java-like Object class simplify containers in C?

FAQ 28.08 Can a Java-like Object class simplify containers in C++?

graphics/new_icon.gif

No, that usually makes things worse!

Java is not C++. C++ is not Java. Just because something works well in Java doesn't mean it will work well in C++ or vice versa. Java has automatic garbage collection, C++ has destructors (FAQ 2.20); Java has a ubiquitous base class Object, C++ has templates (FAQ 2.15). For a lot of reasons, Java's container classes all take Object pointers, and they work well. It's possible to do the same thing in C++, but in C++ this technique tends to be more complex and expensive than using templates. For example, when Fred objects are inserted into a list of Object*, the only thing that is known about them is that they are some kind of Object. When these objects are accessed from the list, the programmer has to carefully find out what the objects really are and typically has to downcast the Object* before anything useful can be done with the objects. This is another form of dynamic type checking, and it can be expensive to write, test, and maintain (see FAQ 27.03).

Forcing things to inherit from a common base class such as Object is called the based object approach. See the next FAQ for more details on these heterogeneous containers.



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