This commit is contained in:
hugogogo
2022-03-06 21:50:26 +01:00
parent c705276319
commit 7abaa2a294
4 changed files with 166 additions and 0 deletions

77
d06/ex02/main.cpp Normal file
View File

@@ -0,0 +1,77 @@
#include <iostream>
#include <cstdlib>
#include <exception>
#include "Classes.hpp"
Base * generate() {
Base *base;
srand (time(NULL));
int i = rand() % 3;
if (i == 0)
{
std::cout << "A\n";
base = new A();
}
else if (i == 1)
{
std::cout << "B\n";
base = new B();
}
else
{
std::cout << "C\n";
base = new C();
}
return base;
}
void identify(Base* p) {
A * a;
B * b;
C * c;
a = dynamic_cast<A *>(p);
if ( a != NULL)
std::cout << "A\n";
b = dynamic_cast<B *>(p);
if ( b != NULL)
std::cout << "B\n";
c = dynamic_cast<C *>(p);
if ( c != NULL)
std::cout << "C\n";
}
void identify(Base& p) {
Base base;
try {
base = dynamic_cast<A&>(p);
std::cout << "<A> ";
}
catch ( std::exception ) {std::cout << "<not A...> ";}
try {
base = dynamic_cast<B&>(p);
std::cout << "<B> ";
}
catch ( std::exception ) {std::cout << "<not B...> ";}
try {
base = dynamic_cast<C&>(p);
std::cout << "<C> ";
}
catch ( std::exception ) {std::cout << "<not C...> ";}
std::cout << "\n";
}
int main() {
Base *base = generate();
identify(base);
identify(*base);
delete base;
return 0;
}