Casting - Why Should I do it for Upcasting

Question!

I have been reading some other threads on this site, and they mention how dynamic_cast and static_cast are both safe for upcasting.

Why are these even required for upcasting?

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 am also from a Java background where conversion for upcasting is unnecessary.

I also read on this site that dynamic_cast is not needed for downcasting [in question "When should static_cast, dynamic_cast and reinterpret_cast be used?"] . Again, I would think that casting is only really necessary when you are downcasting since upcasting occurs automatically.

Where am I wrong?



Answers

Why are these even required for upcasting?

They aren’t, and using them for upcasts is (IMHO) misleading: no cast is required for a reason: logically, a subclass object is-an instance of the superclass.

In summary, I would discourage explicit upcasts. For people who insist on that I demand consistency at least: use explicit upcasts everywhere, including in initialisations:

A * ptr{static_cast


In case of multiple inheritance (which Java doesn't really have) you will possibly adjust your "this" pointer. In that case a reinterpret_cast is not safe, which is what they are trying to emphasize by saying that static_cast and dynamic_cast are safe.

As a small note, in an investigation in a codebase that was to be ported to Android-without-dynamic_cast I found 127 dynamic_casts, of which 122 were not actually necessary. This was code written by people that were OK to very proficient in C .

By : dascandy


This video can help you solving your question :)
By: admin