简体   繁体   中英

C++ dynamic_cast

class A
{
};

class B:public A
{
};
int main()
{
    A a;
    B b;
    A *ap = &b;
    B *bp = dynamic_cast<B*>(ap);
    if(bp!= NULL)
       cout<<"Pass"<<endl;
    else
       cout<<"Fail"<<endl;
    return 0;
}

Why should class A be virtual if you want to do a dynamic cast?

dynamic_cast works differently from static_cast . The results of a static_cast are always a pointer. However, if the cast is incorrect (to a type that the given pointer wasn't originally), then the result of the cast is undefined; the pointer is not necessarily valid. Thus, there is some degree of uncertainty when casting to derived classes with static_cast ; there is no mechanism to prevent you from casting to the wrong things.

dynamic_cast will return either a valid pointer if the cast is correct, or a null pointer if it is incorrect. Thus, the results are well-defined in all cases. In order to do this, dynamic_cast must be dynamic . This means that it has to do runtime checks on the pointer to see if the type being cast to is a legal cast operation.

C++ forbids casts for non-virtual types due to the "pay for what you use" principle: a type that doesn't have virtual functions is generally not a type that you're passing around by its base classes. Inheritance without virtuals is primarily about using the existing implementation, not about specializing functions. Even something as simple as a virtual destructor is sufficient.

The machinery needed to do dynamic_cast is non-zero. So, under the "pay for what you use" principle, only those classes where it would be useful pay for them. IE: those classes which are virtual.

The output will be something along the lines:

Error xxxx: invalid parameter to dynamic_cast . Class is of non-polymorphic type.

The classes need to be polymorphic because that's the specification for dynamic_cast . Internally, dynamic_cast checks virtual table pointers, but that's an implementation detail.

You can use static_cast in this case.

virtual is the key of polymorphysm. A virtual function means it is "overriddenable" by a derived class, otherwise there is no polymorphysm between the classes, there is just inheritance. If the classes are not polymorphic, the dynamic_cast cannot be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM