Static_cast and link to pointers

Can someone tell me why this is not compiling:

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 listing with:

B* b1 = static_cast<B*>(a);

then it compiles.

Edit: Obviously, the compiler treats A*and B*as independent types, otherwise it would work. The question is why is this desirable?

+3
source share
4 answers

B A, B* A*. B A, . ( ). A B*& B*, .

+5

lvalue (B * &) (A *).

+3

A* B*. . , , .

, dynamic_cast , , .

0
source

Link processing is what the compiler does for you, no need to resort to a link.

If we reorganize the code into:

B b;
A* a = &b;
B* b_ptr = static_cast<B*>(a);
B*& p1 = b_ptr;

It will be compiled.

0
source

All Articles