1 #include <stdio.h> 2 3 #include <string> 4 #include <typeinfo> 5 6 #include <Directory.h> 7 #include <File.h> 8 9 using std::string; 10 11 struct A { 12 A() {} 13 virtual ~A() {} 14 15 int a; 16 }; 17 18 struct B : A { 19 B() {} 20 virtual ~B() {} 21 22 int b; 23 }; 24 25 struct C : A { 26 C() {} 27 virtual ~C() {} 28 29 int c; 30 }; 31 32 template<typename A, typename B, typename C> 33 static void 34 rtti_test(A *a, const char *inputClass, const char *classNameA, 35 const char *classNameB, const char *classNameC) 36 { 37 printf("class %s\n", inputClass); 38 printf(" dynamic_cast<%s*>(a): %p\n", classNameA, dynamic_cast<A*>(a)); 39 printf(" dynamic_cast<%s*>(a): %p\n", classNameB, dynamic_cast<B*>(a)); 40 printf(" dynamic_cast<%s*>(a): %p\n", classNameC, dynamic_cast<C*>(a)); 41 const std::type_info *info = &typeid(*a); 42 printf(" typeinfo: %p, name: %s\n", info, (info ? info->name() : NULL)); 43 } 44 45 int 46 main() 47 { 48 // test with artificial classes defined in this file 49 50 #define RTTI_TEST(obj, className) rtti_test<A, B, C>(obj, className, \ 51 "A", "B", "C") 52 53 A a; 54 B b; 55 C c; 56 57 printf("A: %p (vtable: %p)\n", &a, *(void**)&a); 58 printf("B: %p (vtable: %p)\n", &b, *(void**)&b); 59 printf("C: %p (vtable: %p)\n", &c, *(void**)&c); 60 61 RTTI_TEST(&a, "A"); 62 RTTI_TEST(&b, "B"); 63 RTTI_TEST(&c, "C"); 64 65 66 // test with real classes defined in a library 67 68 #undef RTTI_TEST 69 #define RTTI_TEST(obj, className) rtti_test<BNode, BFile, BDirectory>(obj, \ 70 className, "BNode", "BFile", "BDirectory") 71 72 BNode node; 73 BFile file; 74 BDirectory dir; 75 76 printf("BNode: %p (vtable: %p)\n", &node, *(void**)&node); 77 printf("BFile: %p (vtable: %p)\n", &file, *(void**)&file); 78 printf("BDirectory: %p (vtable: %p)\n", &dir, *(void**)&dir); 79 80 RTTI_TEST(&node, "BNode"); 81 RTTI_TEST(&file, "BFile"); 82 RTTI_TEST(&dir, "BDirectory"); 83 84 return 0; 85 } 86