Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          casts/casts2-compilable.cc - The compilable parts of the program from above.Lecture 3 - slide 6 : 27
Program 4

// The compilable parts of the previous program. 

#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* 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.
}