If I have different subclasses of something and an algorithm that works with instances of these subclasses, and if the behavior of the algorithm changes slightly depending on which particular subclass is an instance, then the most common object-oriented way is using virtual methods.
For example, if the subclasses are DOM nodes, and if the algorithm should insert a child element of the node, this algorithm differs depending on whether the parent node is a DOM element (which can have children) or a DOM text (which cannot): and therefore the method insertChildren can be virtual (or abstract) in the base class DomNode and is implemented differently in each of the subclasses DomElement and DomText .
Another possibility is to provide instances with a common property whose value can be read: for example, the algorithm can read the nodeType property of the nodeType base class; or for another example, you may have different types (subclasses) of the network packet that have a common packet header, and you can read the packet header to find out what type of packet it has.
I did not use runtime type information, including:
is and as keywords in C #- downcast
- Object.GetType method in dot net
typeid operator in C ++
When I add a new algorithm that depends on the type of subclass, I instead add a new virtual method to the class hierarchy.
My question is when is it advisable to use information such as runtime instead of virtual functions?
c ++ casting c # oop
ChrisW Oct 05 '09 at 14:33 2009-10-05 14:33
source share