Re: some casting questions
Jess wrote:
Hello,
It seems both static_cast and dynamic_cast can cast a base class
pointer/reference to a derived class pointer/reference. If so, is
there any difference between them?
Yes. dynamic_cast will do a runtime-check to see if the object is actually
of that type or one derived from it (presuming you are having a polymorphic
class hiererchy).
In addition, if I have a derived class object and then upcast it to
its base class, which cast operator should I use?
None. You don't need to cast. Derived-to-base conversions are done
implicitly.
Is it static_cast, or, can I simply cast it implicitly without any
operator?
There is no such thing as an "implicit cast".
Does this upcasting remove the derived class portion of the object?
If you really cast an object, yes. That's usually referred to as "slicing".
But usually, you cast pointers or references, in which case no change to
the object is done.
If after the upcasting, I'd like to downcast it again, is it still
possible?
Yes, if you did it on a pointer or reference to the object, you can cast up
and down as much as you want.
I think if the derived class portion of the object is removed
by upcasting, then it's impossible to downcast it again, but should be
possible otherwise.
Right.