简体   繁体   中英

different behavior of static_cast and dynamic_cast in a specific scenario

I don't figure out the real difference between static_cast and dynamic_cast in below scenario:

                                **///with static_cast///**
    class Foo{};
    class Bar: public Foo
    {
        public:
          void func()
          {
            return;
          }
    };

    int main(int argc, char** argv)
    {
        Foo* f = new Foo;
        Bar* b = static_cast<Bar*>(f);
        b->func();
        return 0;
    }

Output:

Successfully Build and Compiled!

                                **///with dynamic_cast///**
    class Foo{};
    class Bar: public Foo
    {
        public:
          void func()
          {
            return;
          }
    };

    int main(int argc, char** argv)
    {
        Foo* f = new Foo;
        Bar* b = dynamic_cast<Bar*>(f);
        b->func();
        return 0;
    }

Output:

main.cpp: In function 'int main(int, char**)': main.cpp:26:34: error: cannot dynamic_cast 'f' (of type 'class Foo*') to type 'class Bar*' (source type is not polymorphic) Bar* b = dynamic_cast(f);

I'd be appreciated if someone could help me understand this!

The hint is in the part

(source type is not polymorphic)

It means, for dynamic_cast to work, it needs a polymorphic base class, ie have a virtual method

class Foo {
public:
    virtual ~Foo() {}
};

Apart from that, it will not work, because f does not point to a Bar object. dynamic_cast will return a nullptr in this case, which you must check

Foo* f = new Foo;
Bar* b = dynamic_cast<Bar*>(f);
if (b != nullptr)
    b->func();

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