5-2-2: why only virtual base class???

Moderators: david ward, misra cpp

Post Reply
dg1980
Posts: 109
Joined: Wed Apr 27, 2016 2:33 pm
Company: Elektrobit Automotive GmbH

5-2-2: why only virtual base class???

Post by dg1980 » Mon Jan 22, 2018 8:15 am

Hi,

the code below crashes as a result of the undefined behavior referenced in this rule.
Yet, no virtual base class is used as stated in the headline, the text and the example.
So, i think it could mislead any static analysis tool vendor when implementing this rule.

Code: Select all

namespace nMISRA
{
  typedef signed int si32;

  class cBase
  {
  public:
    virtual void f1(void){}
  private:
  };

  class cDerived : public cBase// no virtual base
  {
  public:
    cDerived(void) : x(0){}
    void f2(void){++x;}
  private:
    si32 x;
  };

  void undefined_behaviour(cBase* arg_ptr)
  {
    cDerived* ptr = static_cast<cDerived*>(arg_ptr);// undefined as per ISO/IEC 14882:2003 5.2.9 subsection 8
    ptr->f2();
  }
}

nMISRA::si32 main(void)
{
  nMISRA::cBase b;
  nMISRA::undefined_behaviour(&b);
  return 0;
}

misra cpp
Posts: 148
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: 5-2-2: why only virtual base class???

Post by misra cpp » Tue Apr 17, 2018 1:17 pm

Rule 5-2-2 is there specifically to catch undefined behaviour with virtual bases.

However, your example violates a different rule: 5-2-3

We are considering changes to 5-2-2 for the next version
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.5 Expressions (C++)”