Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ does reinterpret_cast always return the result?

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

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 how I am calling "def", I am wondering if reinterpret_cast actually returns a pointer of type B to be sent off as the parameter to def. I would appreciate any help. Thanks

like image 596
mike bayko Avatar asked Dec 13 '22 22:12

mike bayko


1 Answers

reinterpret_cast will always do what you say - it is a sledghammer. You can do

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

or

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

it will always return a pointer that might point at the correct type. It assumes you know what you are doing

like image 127
pm100 Avatar answered Dec 28 '22 06:12

pm100