Implementation of dynamic_cast
The following code produces this output:
1 is a null pointer
2 is not a null pointer
Code
class base {};
class derived1: public base {};
class derived2: public base {};
int main() {
base *baseptr[1];
baseptr[0] = new derived2;
derived1 *derptr = new deri开发者_JAVA百科ved1;
derived1 *derivedptr1 = dynamic_cast<derived1*>(baseptr[0]);
derived1 *derivedptr2 = dynamic_cast<derived1*>(derptr);
cout<<((derivedptr1==0)?"1 is null pointer":"1 is not a null pointer") << endl;
cout<<((derivedptr2==0)?"2 is null pointer":"2 is not a null pointer") << endl;
}
Why is derivedptr2 only initialised and derivedptr1 is not? As both have a valid right hand side value. Does this have something to do with dynamic cast and the fact that in second case I am casting a derived1* to a derived1*?
Firstly, your code is not compilable. In order to use dynamic_cast
for anything else than upcasts you need a polymorphic type as the pointer operand. You are using it for [an attempted] cross-cast and your types are not polymorphic.
Secondly, if you make your classes polymorphic (so that the code compiles), then the behavior you report is really the expected behavior. The derivedptr1
pointer should indeed be null since derived2
object is not a derived1
object (and the objects in question are not parts of any common superobject). The cross-cast fails, and the dynamic_cast
therefore evaluates to a null pointer. Did you expect anything else?
In the second case (for derivedptr2
) you have an "identity" cast of derived1 *
to derived1 *
. The type is the same, so this cast is essentially a no-op. It just evaluates to the original value.
*dynamic_cast* is used to check the validity of the downcast.
It returns a valid pointer if the pointer actually points to a type being casted to or a class derived from the class being pointed to.
baseptr[0]
points to the type derived2
.
With
dynamic_cast<derived1*>(baseptr[0]);
You are trying to check if basepte[0]
actually points to derived1
or a class derived from it. Obviously, its neither so it returns a 0
.
Similary, derptr
is pointing to a type derived1
.
With
dynamic_cast<derived1*>(derptr);
You are trying to check if derptr
points to derived1
, which is correct, hence it returns a valid pointer type, resulting in prints to Not null.
A Caveat: As @AndreyT rightly pointed out dynamic_cast
only works for Polymorphic
classes!
精彩评论