// Illustration of dynamic_cast in a classical polymorphic situation. #include #include using namespace std; class A { public: virtual void f(){ cout << "Here is f in A" << endl; } }; class B: public A { public: void f() override{ cout << "Here is f in B" << endl; } }; int main(){ A* a = new B{}; // a can point to a B-object a->f(); // Here is f in B B* b1 = a; // error: invalid conversion from A* to B* b1->f(); B* b2 = dynamic_cast(a); // Now OK with dynamic cast b2->f(); // Here is f in B. // Attempting to enforce calling f from A from b2: dynamic_cast(b2)->f(); // Here is f in B. Not successful. static_cast(b2)->f(); // Here is f in B. Not successful. b2->A::f(); // Here is f in A. OK - thats the way to do it. }