casts/casts2.cc - Example of dynamic casting in C++. | Lecture 3 - slide 6 : 27 Program 3 |
// Illustration of dynamic_cast in a classical polymorphic situation. #include <iostream> #include <string> 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<B*>(a); // Now OK with dynamic cast b2->f(); // Here is f in B. // Attempting to enforce calling f from A from b2: dynamic_cast<A*>(b2)->f(); // Here is f in B. Not successful. static_cast<A*>(b2)->f(); // Here is f in B. Not successful. b2->A::f(); // Here is f in A. OK - thats the way to do it. }