dynamic_cast: Cast from Derived * to Base * : derived class « Class « C++ Tutorial






#include <iostream>
using namespace std;

class Base {
public:
  virtual void f() {
     cout << "Inside Base\n";
  }
};

class Derived : public Base {
public:
  void f() {
     cout << "Inside Derived\n";
  }
};

int main()
{
  Base *bp, b_ob;
  Derived *dp, d_ob;

  bp = dynamic_cast<Base *> (&d_ob);
  if(bp) {
    cout << "Cast from Derived * to Base * OK.\n";
    bp->f();
  } else
    cout << "Error\n";


  cout << endl;

  return 0;
}
Cast from Derived * to Base * OK.
Inside Derived








9.18.derived class
9.18.1.Add a constructor to derived class
9.18.2.Call base's constructor and destructor from derived class
9.18.3.Access member of base and use member of derived class
9.18.4.Overriding a base class method in a derived class
9.18.5.Hiding methods
9.18.6.Calling base method from overridden method.
9.18.7.Using virtual methods
9.18.8.Inherit base class twice
9.18.9.dynamic_cast: Cast from Derived * to Base *