Casting - why should I do this to increase

I read some other topics on this site and they mention how dynamic_cast and static_cast are safe to promote.

Why are they even needed for promotion?

For example, if class B is derived from A, then

A * ptr = new B ();

still works and behaves like an object of type A. (I'm also from a Java background, where conversion to level up is undesirable.

I also read on this site that dynamic_cast is not needed for downcasting [in the question When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used? "], Again, I would have thought that casting is really only necessary when you go down, as the increase happens automatically.

Where am I mistaken?

+5
source share
3 answers

If you have a complex inheritance hierarchy, the default behavior may not work by default. Consider, for example:

struct A {};
struct B : A {};
struct C : A {};
struct D : B, C {};

In this hierarchy, a type object Dhas two different type bases A. Converting from D*to is A*ambiguous. For this type of case, you can force it to go through an intermediate step.

A *p = static_cast<B*>(d);   // Give me the 'A' subobject within 'B'

Similarly, if there is a function with several overloads that can accept either a base or a derived type, and you need to call a version using the base type (note: this smells like code!), Then you can use translation to directly allow overloading. Again, if you need to redirect overload resolution, you are probably doing something else wrong.

(.. ), , , , .

+3

( Java ) , , "this". reinterpret_cast , , , , static_cast dynamic_cast .

, , Android--dynamic_cast, 127 _casts, 122 . , , , ++.

+1

?

arent, upcasts (IMHO) : - : , - .

, upcasts. , , , , : upcasts , :

A * ptr{static_cast<A*>(new B)};

, .

0

All Articles