Search code examples
c++castingpolymorphismmisra

MISRA C++ 2008 Rule 5-2-3 Advisory: Casts from a base class to a derived class should not be performed on polymorphic types


In the following example:

class A
{
public:
    A();
    virtual ~A();
    int getID() const;

private:
    int m_ID;
};

Class B : public A
{
public:
    B();
    virtual ~B();
    int getBid() const;

private:
    int m_Bid;
};

bool test(const A* const p_A)
{
    if(5U == static_cast<const B* const>(p_A)->getBid())
    {
         ....
    }
    else
    {
         ...
    }
}

I have MISRA 5-2-3 reported, but i don't now how to resolve it.

MISRA 5-2-3: Casts from a base class to a derived class should not be performed on polymorphic types.


Solution

  • The MISRA checker is right. You should not do a static_cast.

    You need to understand Polymorphism better. When calling your function

    bool test(const A* const p_A)
    

    also a pointer to the derived class can be used. And, by using the vtable, the correct function will be used. So, do not downcast.

    But, you must update your base class. Please add a pure virtual function

    virtual int getBid() const = 0; 
    

    In the base class. Then you can override the this function in your derived class.

    int getBid() const override;
    

    If then a other function calls your bool test(const A* const p_A) with a pointer to the derived class, then the correct function will be called.