Something went wrong. Try again.
Java--'s type casting projects.intra.42.fr/projects/cpp-module-06
Something went wrong. Try again.
1.6 kB · 73 lines
C++
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374#include <iostream>#include <cstdlib>#include <ctime>#include <Base.hpp>#include <A.hpp>#include <B.hpp>#include <C.hpp>
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<const A*>(base) != NULL) std::cout << base << " is A" << std::endl; else if (dynamic_cast<const B*>(base) != NULL) std::cout << base << " is B" << std::endl; else if (dynamic_cast<const C*>(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<const A&>(base); std::cout << &reference << " is A" << std::endl; return; } catch (...) {}
try { const B& reference = dynamic_cast<const B&>(base); std::cout << &reference << " is B" << std::endl; return; } catch (...) {}
try { const C& reference = dynamic_cast<const C&>(base); std::cout << &reference << " is C" << std::endl; return; } catch (...) {}}
int main() { std::srand(static_cast<unsigned int>(std::time(NULL)));
const Base* base = generate();
if (base == NULL) return EXIT_FAILURE;
identify(*base); identify(base);
delete base;}