I
Ian Collins
Daniel said:There are occasions when the interface forces your hand. For example
when implementing the W3C Document Object Model, where all of the
container types are collections of the the base object (Node). Node is
seldom used, most containers end up storing derived objects (Elements or
Attributes) that extend the functionality of Node.
Say you have an element type with an attribute you want to use (the link
in an XHTML anchor element for instance) and you wish to process all of
these elements in a document. The DOM interface provides a means of
extracting a list of them by name, but that list is a list of Nodes and
Node doesn't even have attributes!
I prefer to be able to write something like
dom::NodeList anchors(document.getElementsByTagName("A"));
html::Anchor a(anchors[n]);
and let the library do the conversion from Node to Anchor under the
hood. One benefit of using dynamic_cast is the conversion will fail if
the Node isn't the expected type.
I will be happy to grant that if you are coding in a representational
style instead of Object Oriented, you may very well have to use
dynamic_cast. I don't code that way, nor do any of the libraries I
use.
OK, given an interface with the restrictions I mentioned above, how
would you code it in an "OO" style?