Maestro
Maestro

Reputation: 2572

C++ primer 5th edition: dynamic_cast

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 , a public base class of the target type , or the same as the target type . If e has one of these types, then the cast will succeed. Otherwise, the cast fails. If a dynamic_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.

Thank you.

Upvotes: 1

Views: 89

Answers (1)

eerorika
eerorika

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

Related Questions