123456789101112131415161718192021222324252627282930313233
#include <iostream> #include <exception> using namespace std; class CBase { virtual void dummy() {} }; class CDerived: public CBase { int a; public: void show() { cout<<"here\n"; } }; int main () { try { CBase * pba = new CDerived; CBase * pbb = new CBase; CDerived * pd; pd = dynamic_cast<CDerived*>(pba); if (pd==0) cout << "Null pointer on first type-cast" << endl; pd = dynamic_cast<CDerived*>(pbb); if (pd==0) cout << "Null pointer on second type-cast" << endl; cout<<pd<<endl; //shows null pd->show(); // works ???? !!!!!! } catch (exception& e) {cout << "Exception: " << e.what();} return 0; }
12345678910111213141516171819202122232425
#include <iostream> using namespace std; class X { private: int x; public: void dispX() { x = 1; cout << x << endl; } }; int main() { X* ptr = 0; ptr->dispX(); // fails return 0; }