简体   繁体   中英

Is There a way to use dynamic_cast When Casting to a Child?

Say that I that I have these classes:

struct Parent {};
struct Child : public Parent {
    void func() {}
};

Now say that I wanted to create a function like this:

void foo(Parent* arg) {
    auto child = dynamic_cast<Child*>(arg);

    if(child != nullptr) child->func();
}

But obviously that will obviously give me the error:

dynamic_cast : Parent is not a polymorphic type

So I can't do the dynamic_cast step, is there a way that I can validate that arg is in fact a Child* at run-time?

Give your Parent class a virtual function. Destructor comes into mind, for several reasons (like deleting child via base ptr, etc.).

No, you can't. The information you can get about an object at runtime is achieved using the RTTI ( Run Time Type Information ). The RTTI of an object is stored within the virtual table of it's class.

Each object of a polymorphic class (ie a class which has one or more virtual functions, or a class which is derived from a polymorphic class) contains a vptr , which is a pointer to the virtual table of the corresponding class. An object of a non-polymorphic type has no vptr and there is not a virtual table for its class. Therefore you cannot use dynamic_cast on non-polymorphic types.

So, as @lorro said, you should add a virtual function to Parent , and the simplest option is adding a virtual destructor (which you should do anyway):

struct Parent {
    virtual ~Parent() {} 
};

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