#include #include #include #include #include #include #include static Base* generate() { std::cout << "Generating..." << std::endl; switch (std::rand() % 3) { case 0: std::cout << "A" << std::endl; return new A(); case 1: std::cout << "B" << std::endl; return new B(); case 2: std::cout << "C" << std::endl; return new C(); } std::cout << "What the sigma?" << std::endl; return NULL; } static void identify(const Base* base) { std::cout << "Identifying..." << std::endl; if (dynamic_cast(base) != NULL) std::cout << base << " is A" << std::endl; else if (dynamic_cast(base) != NULL) std::cout << base << " is B" << std::endl; else if (dynamic_cast(base) != NULL) std::cout << base << " is C" << std::endl; } static void identify(const Base& base) { std::cout << "Identifying..." << std::endl; try { const A& reference = dynamic_cast(base); std::cout << &reference << " is A" << std::endl; return; } catch (...) {} try { const B& reference = dynamic_cast(base); std::cout << &reference << " is B" << std::endl; return; } catch (...) {} try { const C& reference = dynamic_cast(base); std::cout << &reference << " is C" << std::endl; return; } catch (...) {} } int main() { std::srand(static_cast(std::time(NULL))); const Base* base = generate(); if (base == NULL) return EXIT_FAILURE; identify(*base); identify(base); delete base; }