/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: narnaud +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/09/29 10:09:08 by narnaud #+# #+# */ /* Updated: 2022/09/29 10:36:06 by narnaud ### ########.fr */ /* */ /* ************************************************************************** */ #include #include #include #include #include "Base.hpp" #include "A.hpp" #include "B.hpp" #include "C.hpp" Base *generate (void) { int rand_id; char names[3] = {'A', 'B', 'C'}; std::srand(time(NULL) * std::rand()); rand_id = std::rand() % 3; std::cout << "Generated a " << names[rand_id] << std::endl; switch (rand_id) { case 0: return new A; break; case 1: return new B; break; case 2: return new C; break; default: return NULL; } } void identify(Base *ptr) { A *a = dynamic_cast(ptr); if (a) std::cout << "Identified a A" << std::endl; B *b = dynamic_cast(ptr); if (b) std::cout << "Identified a B" << std::endl; C *c = dynamic_cast(ptr); if (c) std::cout << "Identified a C" << std::endl; } void identify(Base &ref) { try { A a = dynamic_cast(ref); std::cout << "Identified a A" << std::endl; } catch (std::exception &e) { (void)e;} try { B b = dynamic_cast(ref); std::cout << "Identified a B" << std::endl; } catch (std::exception &e) { (void)e;} try { C c = dynamic_cast(ref); std::cout << "Identified a C" << std::endl; } catch (std::exception &e) { (void)e;} } int main(void) { Base *ptr; std::cout << "Identify from pointer:" << std::endl; for (int i = 0; i < 5; i++) { ptr = generate(); identify(ptr); delete ptr; } std::cout << "Identify from reference:" << std::endl; for (int i = 0; i < 5; i++) { ptr = generate(); identify(*ptr); delete ptr; } }