To understand, let's consider below code snippet:
struct Foo{};
struct Bar{};
int main(int argc, char** argv)
{
Foo* f = new Foo;
Bar* b1 = f; // (1)
Bar* b2 = static_cast<Bar*>(f); // (2)
Bar* b3 = dynamic_cast<Bar*>(f); // (3)
Bar* b4 = reinterpret_cast<Bar*>(f); // (4)
Bar* b5 = const_cast<Bar*>(f); // (5)
return 0;
}
Only line (4) compiles without error. Only reinterpret_cast can be used to convert a pointer to an object to a pointer to an any unrelated object type.
One this to be noted is: The dynamic_cast would fail at run-time, however on most compilers it will also fail to compile because there are no virtual functions in the struct of the pointer being casted, meaning dynamic_cast will work with only polymorphic class pointers.
When to use C++ cast: