C ++ reinterpret_cast always return result?

I have two classes: A and B. A is the parent class of B, and I have a function that takes a pointer to a class of type A, checks if it is also of type B, and if so it calls another function that takes a pointer to a class of type B. When a function calls another function, I provide the parameter reinterpret_cast (a) as a parameter. If this seems ambiguous, here is a sample code:

void abc(A * a) {
  if (a->IsA("B")) { //please dont worry much about this line,
                     //my real concern is the reinterpret_cast
    def(reinterpret_cast<B *>(a));
  };
};

So, now that you know what I call "def", I wonder if reinterpret_cast really returns a pointer of type B to send as a def parameter. I would be grateful for any help. Thanks

+4
source share
5

B*, reinterpret_cast - .

, B, static_cast, , dynamic_cast ( dynamic_cast , nullptr)

. fooobar.com/questions/525/...

+3

reinterpret_cast , - sledghammer.

def(reinterpret_cast<B *>(42));

std::string hw = "hello";
def(reinterpret_cast<B *>(hw));

, . , , .

+5

reinterpret_cast . , ,

 union { 
     TypeA anA;
     TypeB aB;
 } a;

 reinterpret_cast< B* >( a );

, a anA aB.

, static_cast < > , . B A ( ).

static_cast , , dynamic_cast < > . , B - A.

, dynamic_cast<B*>( a ) static_cast< B*>( a ) , .

, vtables. , static_cast, dynamic_cast , .

, dynamic_cast static_cast , - , reinterpret_cast . , , .

+2

Reinterpret cast . , B.

B , A , .

For your use, you should use static translation, which has the advantage that the compiler checks to see if B is really derived from A and does any necessary configuration. No execution overhead is performed by additional checks, but there will be no warnings if the object is not of type B and the program will not be executed arbitrarily.

+1
source

As others have argued, the reinterpret_castwrong solution, use dynamic_cast:

void abc(A * a) {
    B *b = dynamic_cast<B*>(a);
    if (b) {
        def(b);
    }
}
+1
source

Source: https://habr.com/ru/post/1681222/


All Articles