MISRA Discussion Forums
5-2-7 reinterpret_cast between derived classes? - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19)
+---- Forum: 6.5 Expressions (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=134)
+---- Thread: 5-2-7 reinterpret_cast between derived classes? (/showthread.php?tid=1310)



5-2-7 reinterpret_cast between derived classes? - paetzold - 13-02-2017

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:
class B {};
class D : public B {};

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



Re: 5-2-7 reinterpret_cast between derived classes? - dg1980 - 15-02-2017

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


Re: 5-2-7 reinterpret_cast between derived classes? - paetzold - 15-02-2017

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)?


Re: 5-2-7 reinterpret_cast between derived classes? - misra cpp - 10-07-2017

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