Can anyone tell me why this doesn't compile:
struct A { };
struct B : public A { };
int main()
{
B b;
A* a = &b;
B* &b1 = static_cast<B*&>(a);
return 0;
}
Now, if you replace the static cast with:
B* b1 = static_cast<B*>(a);
then it does compile.
Edit: It is obvious that the compiler treats A*
and B*
as independent types, otherwise this would work. The question is more about why is that desirable?
B
is derived from A
, but B*
isn't derived from A*
.
A pointer to a B
is not a pointer to an A
, it can only be
converted to one. But the types remain distinct (and the
conversion can, and often will, change the value of the
pointer). A B*&
can only refer to a B*
, not to any other
pointer type.