In C++, dynamic_cast is mainly used for safe downcasting at run time. To work on dynamic_cast there must be one virtual function in the base class. A dynamic_cast works only polymorphic base class because it uses this information to decide safe downcasting.
```
#include <iostream>
using namespace std;
class Base {
virtual void print() { cout << "Base" << endl; }
};
class Derived : public Base {
void print() { cout << "Derived" << endl; }
};
int main()
{
Derived d;
Base* bp = &d;
Derived* dp = dynamic_cast<Derived*>(bp);
if (dp == nullptr)
cout << "null" << endl;
else
cout << "not null" << endl;
return 0;
}
// not null
```