Different behavior of static_cast and dynamic_cast in a specific scenario

I do not see the real difference between static_cast and dynamic_cast in the following 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;
    }

Conclusion:

Successfully compile and compile!

                                **///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;
    }

Conclusion:

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

I would appreciate if someone would help me figure this out!

+4
source share
1 answer

Tooltip is in part

(source type is not polymorphic)

, dynamic_cast , ..

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

, , f Bar. dynamic_cast nullptr ,

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

Source: https://habr.com/ru/post/1693231/


All Articles