#include <iostream>
#include <typeinfo>
struct A
{
virtual ~A() {}
virtual int get_it() const { return i ; }
int i = 3 ;
};
struct B : A
{
virtual int get_it() const override { return A::get_it() + j ; }
int j = 5 ;
};
int foo( const A& a ) { return a.get_it() ; }
int bar( const A& a )
{
int result = a.i ;
try
{
const B& b = dynamic_cast< const B& >(a) ;
result += b.j ;
}
catch( const std::bad_cast& ) { /* this is not a B */ }
return result ;
}
int main()
{
A a ;
std::cout << foo(a) << ' ' << bar(a) << '\n' ;
B b ;
std::cout << foo(b) << ' ' << bar(b) << '\n' ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dHlwZWluZm8+CgpzdHJ1Y3QgQQp7CiAgICB2aXJ0dWFsIH5BKCkge30KICAgIHZpcnR1YWwgaW50IGdldF9pdCgpIGNvbnN0IHsgcmV0dXJuIGkgOyB9CiAgICBpbnQgaSA9IDMgOwp9OwoKc3RydWN0IEIgOiBBCnsKICAgIHZpcnR1YWwgaW50IGdldF9pdCgpIGNvbnN0IG92ZXJyaWRlIHsgcmV0dXJuIEE6OmdldF9pdCgpICsgaiA7IH0KICAgIGludCBqID0gNSA7Cn07CgppbnQgZm9vKCBjb25zdCBBJiBhICkgeyByZXR1cm4gYS5nZXRfaXQoKSA7IH0KCmludCBiYXIoIGNvbnN0IEEmIGEgKQp7CiAgICBpbnQgcmVzdWx0ID0gYS5pIDsKCiAgICB0cnkKICAgIHsKICAgICAgICBjb25zdCBCJiBiID0gZHluYW1pY19jYXN0PCBjb25zdCBCJiA+KGEpIDsKICAgICAgICByZXN1bHQgKz0gYi5qIDsKICAgIH0KICAgIGNhdGNoKCBjb25zdCBzdGQ6OmJhZF9jYXN0JiApIHsgLyogdGhpcyBpcyBub3QgYSBCICovIH0KCiAgICByZXR1cm4gcmVzdWx0IDsKfQoKaW50IG1haW4oKQp7CiAgICBBIGEgOwogICAgc3RkOjpjb3V0IDw8IGZvbyhhKSA8PCAnICcgPDwgYmFyKGEpIDw8ICdcbicgOwoKICAgIEIgYiA7CiAgICBzdGQ6OmNvdXQgPDwgZm9vKGIpIDw8ICcgJyA8PCBiYXIoYikgPDwgJ1xuJyA7Cgp9Cg==