If I have various subclasses of something, and an algorithm which operates on instances of those subclasses, and if the behaviour of the algorithm varies slightly depending on what particular subclass an instance is, then the most usual object-oriented way to do this is using virtual methods.
For example if the subclasses are DOM nodes, and if the algorithm is to insert a child node, that algorithm differs depending on whether the parent node is a DOM element (which can have children) or DOM text (which can't): and so the insertChildren
method may be virtual (or abstract) in the DomNode
base class, and implemented differently in each of the DomElement
and DomText
subclasses.
Another possibility is give the instances a common property, whose value can be read: for example the algorithm might read the nodeType
property of the DomNode
base class; or for another example, you might have different types (subclasses) of network packet, which share a common packet header, and you can read the packet header to see what type of packet it is.
I haven't used run-time-type information much, including:
- The
is
andas
keywords in C# - Downcasting
- The Object.GetType method in dot net
- The
typeid
operator in C++
When I'm adding a new algorithm which depends on the type of subclass, I tend instead to add a new virtual method to the class hierarchy.
My question is, when is it appropriate to use run-time-type information, instead of virtual functions?