Consider the following sample code.
#include <iostream> using namespace std; class base { public: void func() { cout << "base::func()" << endl; } }; class derived : public base { public: void func() { cout << "derived::func()" << endl; } }; void dummy(base *bptr) { derived *dptr = static_cast<derived*> (bptr); dptr->func(); } int main() { base bob1; derived dob1; dummy(&dob1); //Line1 dummy(&bob1); //Line2 } In Line1, I am passing the address of a derived class object to function dummy which takes a pointer to base class object. So the static_cast in the function dummy is safe.
In Line2, I am passing the address of a base class object to function. So the static_cast in the function dummy is not safe.
But when i execute the code, the program behaves normally. I thought, by the word not safe, the program should crash at run-time. But no crash occurred.
Here is the output which i get.
derived::func() derived::func() What is the reason why the program did not crash at run-time?