TITLE: the intelligent children design pattern CLARKE: Allan Clarke (clarke@ses.com) This is a brief look at the "intelligent children" design pattern for dealing with dual inheritance heirarchies[1]. A dual inheritance heirarchy frequently results from separation of concerns. Consider this example, taken from a graphing package, which separates the mathematical or data model (Nodes) from the presentation (Renderers). class Node { ... }; class Computer : public Node { ... }; class Router : public Node { ... }; class Network : public Node { ... }; class NodeRenderer { ... }; class ComputerRenderer : public NodeRenderer { ... }; class RouterRenderer : public NodeRenderer { ... }; class NetworkRenderer : public NodeRenderer { ... }; In these dual heirarchies, there is typically a one-to-one relationship between instances of associated classes, (i.e., Computer-ComputerRenderer). This relationship is not really dynamic and usually lasts the lifetime of the instances (a typical requirement for using this pattern). The problem this pattern solves is the downcasting problem (typical for strongly typed languages like C++ and Java). For example, the NodeRenderer class will typically have a pointer to the associated Node. Derived Renderers will downcast this pointer to access services specific to the derived Node kind. There is the rub. class NodeRenderer { protected: Node* node; ... }; class ComputerRender : public NodeRenderer { public: void foobar () { Computer* cp = dynamic_cast(node); ... } }; To avoid the downcast, use the "intelligent children design pattern" as shown below class NodeRender { protected: virtual Node* node () = 0; ... }; class ComputerRender : public NodeRenderer { protected: virtual ComputerNode* node () { return computer; } ... private: Computer* computer; }; Note that this relies on a newish feature, called covariance of return types, that may not be implemented for all compilers you encounter. For more details, see the article [1]. Happy Trails. [1] Martin, Robert C. "Design Patterns for Dealing with Dual Inheritance Hierarchies in C++", C++ Report, April 1997.