// RTTI_CAST.cpp : Defines the entry point for the console application.
//
/// Summary:
/// There must have inheritress between Source type and target type.
/// if not, static_cast will bring compile error;
/// dynamic_cast will return false or throw exception.
#include <iostream>
using namespace std;
class A
{
public:
A(int j = 0): i(j)
{
}
virtual ~A() {}
virtual void Output()
{
cout<< i;
}
private:
int i;
};
class B : public A
{
public:
B() : A(1),j(2)
{
}
virtual ~B() {}
virtual void Output()
{
A::Output();
cout<< j<<endl;
}
private:
int j;
};
int _tmain(int argc, _TCHAR* argv[])
{
char a = 'a';
int * pI = static_cast<int*>(&a); // failed.
B b;
A* pA = dynamic_cast<A*>(&b);
pA->Output();
const type_info& aInfo = typeid(A);
const type_info& bInfo = typeid(B);
try
{
B* pB = dynamic_cast<B*>(pA);
pB->Output();
}
catch(bad_cast& e)
{
std::cout<<e.what()<<endl;
}
return 0;
}