Yes, it does compile (http://ideone.com/CXbeh0)
By default A
is copyable. The copy constructor has signature A::A(A const &)
. Since instance of B
is implicitly convertible to A const &
, the cast will be resolved using A
's copy constructor.
The conversion to reference applies to the (also implicitly generated) copy assignment operator too, so a = b
again compiles using A &A::operator=(A const &)
.
Keep in mind, that the new object is of type A, not B, so it does not contain any additional information the original instance of B did. That is rarely what you want.
On a side-note, it is recommended in C++ to forget that C-style cast exists and use the more specific cast types of C++:
- The function-style cast for explicit request to create a temporary of target type using matching constructor; also allows using multi-parameter constructors.
- The
static_cast
, for compatible types only. - The
dynamic_cast
for upcasting pointers/references with run-time check. const_cast
to only handle const.- And
reinterpret_cast
if you really need to play pointer tricks, but beware of aliasing rules.