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!
f(and thereforeb) isn't a pointer to aBarobject.dynamic_cast, this reference should be helpful.dynamic_cast(in case of virtual members) will returnnullptr.static_castwill compile but using such pointer will result in undefined behavior.