You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

90 lines
2.4 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/29 10:09:08 by narnaud #+# #+# */
/* Updated: 2022/09/29 10:36:06 by narnaud ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <cstdlib>
#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<A *>(ptr);
if (a)
std::cout << "Identified a A" << std::endl;
B *b = dynamic_cast<B *>(ptr);
if (b)
std::cout << "Identified a B" << std::endl;
C *c = dynamic_cast<C *>(ptr);
if (c)
std::cout << "Identified a C" << std::endl;
}
void identify(Base &ref) {
try {
A a = dynamic_cast<A&>(ref);
std::cout << "Identified a A" << std::endl;
}
catch (std::exception &e) { (void)e;}
try {
B b = dynamic_cast<B &>(ref);
std::cout << "Identified a B" << std::endl;
}
catch (std::exception &e) { (void)e;}
try {
C c = dynamic_cast<C &>(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;
}
}