Casting references VS Casting the mem address of that reference?
If you want to cast a reference you usually do this:
Code:
Subclass &myref = (Subclass&)base_class_object_ref;
But I have also seen people doing this:
Code:
Subclass &myref = *(Subclass*)&base_class_object_ref;
I understand how it works, but is there any difference? Is there a reason or a specific scenario where I must choose the one over the other?
Thanks :)
Re: Casting references VS Casting the mem address of that reference?
Neither should be used. In C++ you would use a dynamic_cast for a downcast - not a 'c' style cast.
Code:
Subclass &myref = dynamic_cast<Subclass&>(base_class_object_ref);
For an upcast, you don't need to cast.
See https://en.cppreference.com/w/cpp/language/dynamic_cast
Re: Casting references VS Casting the mem address of that reference?
LOL, I thought dynamic cast would fail on a downcast and work only for upcasts. Is it the other way around?
Re: Casting references VS Casting the mem address of that reference?
Quote:
Originally Posted by
babaliaris
LOL, I thought dynamic cast would fail on a downcast and work only for upcasts. Is it the other way around?
Why not try it?
Re: Casting references VS Casting the mem address of that reference?
Quote:
Originally Posted by
babaliaris
LOL, I thought dynamic cast would fail on a downcast and work only for upcasts. Is it the other way around?
read the documentation at the given link.
Re: Casting references VS Casting the mem address of that reference?
Quote:
Originally Posted by
babaliaris
LOL, I thought dynamic cast would fail on a downcast and work only for upcasts. Is it the other way around?
Assigning a derived type to a base type is typesafe meaning the correctness can be checked at compile-time already. Because of that, explicit upcasting is never necessary (although allowed).
An assignment the other way around, from base to derived, is not typesafe and may fail at runtime. To make this perfectly clear the compiler requires the programmer to put in an explicit downcast, either static or dynamic. For a dynamic downcast the compiler inserts a runtime check which means it will fail in a way the programmer can detect and act on, whereas a static downcast will fail in silence.
Since downcasting isn't typesafe the general recommendation is to avoid it. In object oriented (OO) programming, if there are many downcasts this is usually a sign of a design flaw. It could for example be that the functionality exposed by the base type is too limited and so forces the programmer to reach for the derived types. But sometimes downcasting is motivated and then OO offers a typesafe way called the Visitor design pattern.
One of the major benefits of C++ is its strong type checking at compile-time so it's kind of counterproductive to prevent the compiler from doing its job properly by putting in downcasts. And even if a dynamic downcast will catch an assignment error at runtime it comes with a check that adds overhead.