5-2-7 reinterpret_cast between derived classes?

Moderators: david ward, misra cpp

Post Reply
paetzold
Posts: 4
Joined: Thu Jan 26, 2017 2:08 pm
Company: Fresenius Medical Care Deutschland GmbH

5-2-7 reinterpret_cast between derived classes?

Post by paetzold » Mon Feb 13, 2017 4:31 pm

Dear MISRA team,

the term "unrelated type" leads to the question whether casting from a base to derived class pointer type and vice versa using reinterpret_cast shall be covered by the rule or not. Remark: I am perfectly aware that dynamic_cast and static_cast , resp., would be the right way for these purposes, so my question is rather academic.

I refer to the term "related type" as Stroustrup uses it concerning types "in the same class hierarchy" which is surely the case here.

Code: Select all

class B {};
class D : public B {};

void f()
{
    D* dptr = new D();
    B* bptr = reinterpret_cast<B*>( dptr );
    D* dptr2 = reinterpret_cast<D*>( bptr ); // correct (yet ugly) when one knows where the base class pointer points to
}

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

Re: 5-2-7 reinterpret_cast between derived classes?

Post by dg1980 » Wed Feb 15, 2017 10:26 am

Isn't this one already covered by rule 5-2-3?

paetzold
Posts: 4
Joined: Thu Jan 26, 2017 2:08 pm
Company: Fresenius Medical Care Deutschland GmbH

Re: 5-2-7 reinterpret_cast between derived classes?

Post by paetzold » Wed Feb 15, 2017 1:18 pm

Hi,
I don't think that 5-2-3 covers the given situation:
  • 5-2-3 is handling only downcasts whereas my question is about both directions (i.e. casting from a dervied to its base class, too)
  • 5-2-3 is only about polymorphic types, yet not everything which is inherited is necessarily polymorphic: in my example, the classes don't have any virtual functions, or think about private inheritance.
  • 5-2-3 is labeled "advisory", which means that I can assume a project situation where 5-2-3 is not active but 5-2-7 is.
As I have already written: using reinterpret_cast is probably silly since there are better ways to do. But it is possible and someone might actually have a good reason for using it.

The aim of my question is rather general, are derived classes "related" or "unrelated"? Therefore, does rule 5-2-7 apply if you do any pointer conversion (where reinterpret_cast is the most rough one)?

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

Re: 5-2-7 reinterpret_cast between derived classes?

Post by misra cpp » Mon Jul 10, 2017 11:10 am

The rule permits this - but in general, reinterpret_cast will not give the correct result, so should not be used. Indeed there are very few cases where reinterpret_cast should be used. We will address this in the next version
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.5 Expressions (C++)”