Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
5-2-7 reinterpret_cast between derived classes?
#1
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
}
<t></t>
Reply
#2
Isn't this one already covered by rule 5-2-3?
<t></t>
Reply
#3
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)?
<t></t>
Reply
#4
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
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)