This will result in undefined behavior when you try to access the resulting Derived pointer that is actually pointing to a Base object. We talk about exceptions later in this tutorial.
However, you should also consider avoiding casting altogether and just use virtual functions. Instead, these programmers say you should use virtual functions. In general, using a virtual function should be preferred over downcasting. However, there are times when downcasting is the better choice:. Let's look at the code. If you do not understand what's going on, please do not worry, we'll get to it later.
It doesn't give us what type of object a pointer points to. Instead, it answers the question of whether we can safely assign the address of an object to a pointer of a particular type. If the object bound to the pointer is not an object of the target type, it fails and the value is 0. So, if we make the Base class polymorphic by adding virtual function as in the code sample below, it will be compiled successfully.
However, if D is cast to point to an A object, which instance of A would result? This would result in an ambiguous casting error. To get around this problem, you can perform two unambiguous casts. Further ambiguities can be introduced when you use virtual base classes. Class hierarchy that shows virtual base classes. In this hierarchy, A is a virtual base class. You must first cast back to the complete E object, then work your way back up the hierarchy, in an unambiguous manner, to reach the correct B object.
Class hierarchy that shows duplicate base classes. Given an object of type E and a pointer to the D subobject, to navigate from the D subobject to the left-most A subobject, three conversions can be made.
Considering cross casts, it is actually possible to do the conversion from a pointer to D to a pointer to the left-most A subobject in just two steps. I thought I need dynamic casts just in cases, where I'm not sure if the pointer holds the to-casting-pointer or not at runtime. In serialisaton i. A list should be serializeable and a string too, so they are derived classes from one base class. Thank you very much for your help. Added after 54 minutes:.
Replies: 12 Last Post: 5th October , Replies: 5 Last Post: 19th April , Replies: 2 Last Post: 12th October , Replies: 7 Last Post: 7th August ,
0コメント