Re: Problem with static downcast of base type to derived type
On Jul 2, 11:06 pm, acehr...@gmail.com wrote:
On Jul 2, 1:31 pm, Erik Wikstr=F6m <Erik-wikst...@telia.com> wrote:
On 2008-07-02 21:13, Dom Jackson wrote:
Besides that, when casting from base to derived you should
use dynamic_cast and check if the cast succeeded (in which
case the returned pointer will be non-0). If you do that in
your code you will notice that you will always get a
0-pointer.
Of course the OP must have at least one virtual function in
Base for dynamic_cast to work.
Of course, if Base doesn't have at least one virtual function,
there's probably no point in deriving from it.
A cast from pointer to base class to a pointer to derived is
only allowed if the object pointed to is of type derived.
True.
You can always cast from pointer to derived to pointer to
base using static_cast, but when going the other way you
shall use dynamic_cast.
static_cast is fine even for downcasting, as long as the
target type is correct.
Which, of course, means that there is a distinct risk of an
error, resulting in undefined behavior. The choice is basically
whether you want undefined behavior or defined behavior in case
of an error.
static_cast is for when the destination type is known at
compile time.
Static_cast is for many things, but in the case of Base* to
Derived*, it should only be used when the profiler says you have
no other choice. (Practically, of course, there should be very,
very few Base* to Derived* conversions to begin with.)
Did you mean that static_cast can not be used in polymorphic
hierarchies? If so, it's news to me and I don't have the
standard handy to check. :)
It can only be used in limited ways: you can't convert from a
virtual base to a derived (pointer or reference), for example,
and you can't arbitrarily navigate in the hierarchy.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34