From 6169d697a5be59426d034b878bffc848de49491d Mon Sep 17 00:00:00 2001 From: Charles Cabergs Date: Wed, 18 Nov 2020 10:30:31 +0100 Subject: Added cpp06/ex01 and ex02 --- cpp06/ex02/main.cpp | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 90 insertions(+), 2 deletions(-) (limited to 'cpp06/ex02/main.cpp') diff --git a/cpp06/ex02/main.cpp b/cpp06/ex02/main.cpp index 17c0c3d..86cd78f 100644 --- a/cpp06/ex02/main.cpp +++ b/cpp06/ex02/main.cpp @@ -6,12 +6,14 @@ /* By: charles +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/04/15 10:00:18 by charles #+# #+# */ -/* Updated: 2020/04/15 10:05:23 by charles ### ########.fr */ +/* Updated: 2020/11/18 09:29:49 by charles ### ########.fr */ /* */ /* ************************************************************************** */ #include +#include #include +#include #include "Base.hpp" #include "A.hpp" #include "B.hpp" @@ -28,9 +30,95 @@ Base* generate(void) return NULL; } +void identify_from_pointer(Base *p) +{ + if (dynamic_cast(p) != NULL) + std::cout << "A" << std::endl; + else if (dynamic_cast(p) != NULL) + std::cout << "B" << std::endl; + else if (dynamic_cast(p) != NULL) + std::cout << "C" << std::endl; + else + std::cout << "Couldn't identify from pointer" << std::endl; +} + +void identify_from_reference(Base &p) +{ + try + { + (void)dynamic_cast(p); + std::cout << "A" << std::endl; + return; + } + catch (std::exception &e) + {} + try + { + (void)dynamic_cast(p); + std::cout << "B" << std::endl; + return; + } + catch (std::exception &e) + {} + try + { + (void)dynamic_cast(p); + std::cout << "C" << std::endl; + return; + } + catch (std::exception &e) + {} + + std::cout << "Couldn't identify from reference" << std::endl; +} + int main() { - srand(time(NULL)); + int seed; + std::ifstream devRandom("/dev/random"); + if (devRandom.is_open()) + { + devRandom.read((char*)&seed, sizeof(int)); + devRandom.close(); + } + else + { + seed = time(NULL); + } + srand(seed); + + { + std::cout << "=============== IDENTIFY FROM POINTER ===============" << std::endl; + Base *a = new A(); + Base *b = new B(); + Base *c = new C(); + identify_from_pointer(a); + identify_from_pointer(b); + identify_from_pointer(c); + delete a; + delete b; + delete c; + } + + { + std::cout << "=============== IDENTIFY FROM REF ===============" << std::endl; + A a; + B b; + C c; + identify_from_reference(a); + identify_from_reference(b); + identify_from_reference(c); + } + + std::cout << "=============== GENERATE ===============" << std::endl; + for (int i = 0; i < 10; i++) + { + Base *b = generate(); + std::cout << "---" << std::endl; + identify_from_pointer(b); + identify_from_reference(*b); + delete b; + } return 0; } -- cgit