B br = d; // upcast via implicit conversion
This is object slicing. br
is an instance of B
and copies only the B
part of d
. (This implies down-casting of d
to B&
which the compiler can do implicitly because D
is derived from B
.)
D another_d = static_cast<D>(br);
This is the attempt to create an instance of D
from an instance of B
.
While D
is also a B
(due to inheritance) the opposite is not true.
So, there is nothing the compiler can do implicitly.
To make this working, a constructor D(B&)
has to be defined.
To illustrate this: D
might have additional member variables which cannot copied from B
, and this is what such constructor had to handle in any way.
D& another_d = static_cast<D&>(br); // OK
This is not really OK. It might (seem to) work as D
doesn't contain additional member variables.
br
is an instance of B
(not of D
). "Faking" a reference to D
is actually a lie but doing this explicitly (in code) makes the compiler silent. However, it's still wrong.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…