Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

MISRA.CAST.POLY.TYPE

Cast 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.

Rationale

A 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.

Example

class 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.