|
| 1 | +# RTTI - Run Time Type Information |
| 2 | + |
| 3 | +// Run Time Type Information |
| 4 | +``` cpp |
| 5 | +#include <ios> |
| 6 | +#include <iostream> |
| 7 | +using namespace std; |
| 8 | +class Base |
| 9 | +{ |
| 10 | +public: |
| 11 | + Base() { cout << __FUNCTION__ << endl; } |
| 12 | + virtual ~Base() { cout << __FUNCTION__ << endl; } |
| 13 | + virtual void f() |
| 14 | + { |
| 15 | + cout << "Base" << __FUNCTION__ << endl; |
| 16 | + } |
| 17 | +}; |
| 18 | +class Derived : public Base |
| 19 | +{ |
| 20 | +public: |
| 21 | + Derived() { cout << __FUNCTION__ << endl; } |
| 22 | + ~Derived() { cout << __FUNCTION__ << endl; } |
| 23 | + |
| 24 | + void f() |
| 25 | + { |
| 26 | + cout << "Derived-" << __FUNCTION__ << endl; |
| 27 | + } |
| 28 | +}; |
| 29 | +class Derived2 : public Derived |
| 30 | +{ |
| 31 | +public: |
| 32 | + Derived2() { cout << __FUNCTION__ << endl; } |
| 33 | + ~Derived2() { cout << __FUNCTION__ << endl; } |
| 34 | + void f() |
| 35 | + { |
| 36 | + cout << "Derived2-" << __FUNCTION__ << endl; |
| 37 | + } |
| 38 | +}; |
| 39 | +int main(void) |
| 40 | +{ |
| 41 | + Derived* p = new Derived2(); |
| 42 | + cout << "-------------------" << endl; |
| 43 | + p->f(); |
| 44 | + cout << "-------------------" << endl; |
| 45 | + auto p2 = dynamic_cast<Derived2*>(p); |
| 46 | + auto p3 = dynamic_cast<Base*>(p2); |
| 47 | + cout << sizeof(p) << ", " |
| 48 | + << typeid(p).name() << ", " |
| 49 | + << std::hex << typeid(p).hash_code() << endl; |
| 50 | + cout << "p2: " << typeid(p2).name() << ", " |
| 51 | + << std::hex << typeid(p2).hash_code() << endl; |
| 52 | + cout << "p3: " << typeid(p3).name() << ", " |
| 53 | + << std::hex << typeid(p3).hash_code() << endl; |
| 54 | + cout << sizeof(*p) << ", " |
| 55 | + << typeid(*p).name() << ", " |
| 56 | + << std::hex << typeid(*p).hash_code() << endl; |
| 57 | + cout << "-------------------" << endl; |
| 58 | + delete p; |
| 59 | + cout << "-------------------" << endl; |
| 60 | + return 0; |
| 61 | +} |
| 62 | +``` |
| 63 | +
|
| 64 | +!!! experiment "Output" |
| 65 | + ```cpp |
| 66 | + Base |
| 67 | + Derived |
| 68 | + Derived2 |
| 69 | + ------------------- |
| 70 | + Derived2-f |
| 71 | + ------------------- |
| 72 | + 8, P7Derived, 9a7969d972aa52f7 |
| 73 | + p2: P8Derived2, 16a9329eaa369fd5 |
| 74 | + p3: P4Base, 11468d01f070011b |
| 75 | + 8, 8Derived2, f3ec1aaa6ce2faa5 |
| 76 | + ------------------- |
| 77 | + ~Derived2 |
| 78 | + ~Derived |
| 79 | + ~Base |
| 80 | + ------------------- |
| 81 | + ``` |
| 82 | +
|
| 83 | +--- |
0 commit comments