Reputation: 2572
I have this text from C++ Primer 5th edition:
dynamic_cast<type*>(e)
dynamic_cast<type&>(e)
dynamic_cast<type&&>(e)
In all cases, the type of
e
must be either a class type that is publicly derived from the target type , apublic
base class of the target type , or the same as the target type . Ife
has one of these types, then the cast will succeed. Otherwise, the cast fails. If adynamic_cast
to a pointer type fails, the result is 0. If a dynamic_cast to a reference type fails, the operator throws an exception of type bad_cast.
It is said that "the type of e
must be either a class type that publicly derived from the target type..." I think the contrary he meant because if the type of e
is derived from the type cast then we don't need a conversion or cast because they are implicitly convertible by inheritance But normally: the type of type
must be a class type that is publicly derived from the type of e
...
What do you think? Am I correct and this is a mistake in the book?
Thank you.
Upvotes: 1
Views: 89
Reputation: 238461
I think the contrary he meant because if the type of e is derived from the type cast then we don't need a conversion or cast because they are implicitly convertible by inheritance
If the type isn't the same, then there must be a conversion in order to arrive to the target type, whether that conversion is implicit or explicit.
While it's true that we won't need a cast, that doesn't mean that the cast would fail. So no, I don't think they meant the contrary. Upcasts succeed with dynamic cast, the quoted text is correct about that.
But normally: the type of type must be a class type that is publicly derived from the type of e...
That's what the second condition means in the book:
In all cases, the type of e must be either a ..., a public base class of the target type , or ...
Upvotes: 3