MISRA.CAST.POLY.TYPECast from a polymorphic base class to a derived class. MISRA-C++ Rule 5-2-3 (advisory): Casts from a base class to a derived class should not be performed on polymorphic types.RationaleA downcast occurs when a class type is converted to another class type that is derived from that first class. Polymorphism enables strong abstraction between the interface and implementation of a hierarchy. Explicit casts bypass this layer of abstraction resulting in higher levels of coupling and dependency. Exampleclass Colour { /* ... */ }; void setColour ( Colour const & ); class Obj { public: virtual bool hasColour ( ) const = 0; virtual Colour getColour ( ) const = 0; }; class ObjWithColour : public Obj { public: virtual bool hasColour ( ) const { return true; } virtual Colour getColour ( ) const { return m_colour; } private: Colour m_colour; }; void badPrintObject ( Obj const & obj ) { ObjWithColour const * pObj = dynamic_cast<ObjWithColour const*>( &obj ); // Non-compliant if ( 0 != pObj ) { setColour ( pObj->getColour ( ) ); } } void goodPrintObject ( Obj const & obj ) { if ( obj.hasColour ( ) ) { setColour ( obj.getColour ( ) ); } } The function 'badPrintObject' now requires knowledge of how objects in the 'Obj' hierarchy are structured. In the future, the hierarchy may be changed so that objects are split into specific colours, and any clients dependent on the colour will then have to be modified to include this change. Clients using virtual functions however, will remain unchanged. |