Search code examples
c++reinterpret-cast

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


Solution

  • You will have a pointer of type B*, but reinterpret_cast isn't really great.

    If you're sure the type is a B, use static_cast, if not, use dynamic_cast and test the pointer (if dynamic_cast fails, it returns nullptr)

    See https://stackoverflow.com/a/332086/5303336