Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          casts/casts3.cc - dynamic_cast is a predicate - it tests if a pointer is of the appropriate type.Lecture 3 - slide 6 : 27
Program 5

// Illustration of dynamic_cast as a predicate.

#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;
  }
};
// dynamic_casts<T>x in C++ is similar to  x as T  in C#

class C: public A {
  public: 
  void f() override{
    cout << "Here is f in C" << endl;
  }
};

int main(){

  A* a = new B{};                   // a can point to a B-object
  a->f();                           // Here is f in B

  if (B *b = dynamic_cast<B*>(a))   // if(a is of type B*) ...
     b->f();                        // yes: Here is f in B
  else
     cout << "Cannot" << endl;

  if (C *c = dynamic_cast<C*>(a))   // if(a is of type C*))...
     c->f();    
  else
     cout << "Cannot" << endl;      // no: Cannot

}