#include <iostream>
#include <typeinfo>
struct Base
{
virtual void test() { /* ... */ }
};
struct Derived : Base
{
virtual void test() { /* ... */ }
};
int main()
{
Base *bp = new Base;
// null if dynamic_cast is invalid
if (Derived *dp = dynamic_cast<Derived*>(bp) )
{
std::cout << "Dynamic cast with pointer succeeded" << std::endl;
}
else
{
std::cout << "Dynamic cast with pointer failed" << std::endl;
}
Base b;
Base &br = b;
// throws exception if dynamic_cast is invalid
try
{
Derived &dr = dynamic_cast<Derived&>(br);
std::cout << "Dynamic cast with reference succeeded" << std::endl;
}
catch(std::bad_cast)
{
std::cout << "Dynamic cast with reference failed" << std::endl;
}
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dHlwZWluZm8+CgpzdHJ1Y3QgQmFzZQp7CiAgdmlydHVhbCB2b2lkIHRlc3QoKSB7IC8qIC4uLiAqLyB9Cn07CnN0cnVjdCBEZXJpdmVkIDogQmFzZQp7CiAgdmlydHVhbCB2b2lkIHRlc3QoKSB7IC8qIC4uLiAqLyB9Cn07CgppbnQgbWFpbigpCnsKICBCYXNlICpicCA9IG5ldyBCYXNlOwoKICAvLyBudWxsIGlmIGR5bmFtaWNfY2FzdCBpcyBpbnZhbGlkCiAgaWYgKERlcml2ZWQgKmRwID0gZHluYW1pY19jYXN0PERlcml2ZWQqPihicCkgKQogIHsKICAgIHN0ZDo6Y291dCA8PCAiRHluYW1pYyBjYXN0IHdpdGggcG9pbnRlciBzdWNjZWVkZWQiIDw8IHN0ZDo6ZW5kbDsKICB9CiAgZWxzZQogIHsKICAgIHN0ZDo6Y291dCA8PCAiRHluYW1pYyBjYXN0IHdpdGggcG9pbnRlciBmYWlsZWQiIDw8IHN0ZDo6ZW5kbDsKICB9CgoKICBCYXNlIGI7CiAgQmFzZSAmYnIgPSBiOwoKICAvLyB0aHJvd3MgZXhjZXB0aW9uIGlmIGR5bmFtaWNfY2FzdCBpcyBpbnZhbGlkCiAgdHJ5CiAgewogICAgRGVyaXZlZCAmZHIgPSBkeW5hbWljX2Nhc3Q8RGVyaXZlZCY+KGJyKTsKICAgIHN0ZDo6Y291dCA8PCAiRHluYW1pYyBjYXN0IHdpdGggcmVmZXJlbmNlIHN1Y2NlZWRlZCIgPDwgc3RkOjplbmRsOwogIH0KICBjYXRjaChzdGQ6OmJhZF9jYXN0KQogIHsKICAgIHN0ZDo6Y291dCA8PCAiRHluYW1pYyBjYXN0IHdpdGggcmVmZXJlbmNlIGZhaWxlZCIgPDwgc3RkOjplbmRsOwogIH0KfQ==