cpp06/ex02/Main.cpp

104 lines
1.9 KiB
C++

#include "Base.hpp"
#include "A.hpp"
#include "B.hpp"
#include "C.hpp"
#include <cstdlib>
#include <cstdio>
#include <ctime>
// static Base *generate(void)
// {
// switch (rand() % 3)
// {
// case 0:
// std::cout << "create A" << std::endl;
// return (new A());
// break;
// case 1:
// std::cout << "create B" << std::endl;
// return (new B());
// break;
// case 2:
// std::cout << "create C" << std::endl;
// return (new C());
// break;
// default:
// std::cerr << "Error" << std::endl;
// return NULL;
// }
// }
static Base *generate(void)
{
switch (rand() % 3)
{
case 0:
return (new A());
break;
case 1:
return (new B());
break;
case 2:
return (new C());
break;
default:
std::cerr << "Error" << std::endl;
return NULL;
}
}
void identify(Base* p)
{
if (dynamic_cast<A*>(p))
std::cout << "Object is of type A" << std::endl;
else if (dynamic_cast<B*>(p))
std::cout << "Object is of type B" << std::endl;
else if (dynamic_cast<C*>(p))
std::cout << "Object is of type C" << std::endl;
}
void identify(Base& p)
{
try {
(void)dynamic_cast<A&>(p);
std::cout << "Object is of type A" << std::endl;
return;
} catch (std::exception&) {}
try {
(void)dynamic_cast<B&>(p);
std::cout << "Object is of type B" << std::endl;
return;
} catch (std::exception&) {}
try {
(void)dynamic_cast<C&>(p);
std::cout << "Object is of type C" << std::endl;
return;
} catch (std::exception&) {}
}
int main()
{
std::srand(std::time(NULL));
Base* ptr;
/////////////////////////////////
std::cout << "Test 1 PTR: " << std::endl;
ptr = generate();
identify(ptr);
delete ptr;
std::cout << "Test 2 PTR: " << std::endl;
ptr = generate();
identify(ptr);
delete ptr;
//////////////////////////////////
std::cout << "Test 1 REF: " << std::endl;
ptr = generate();
identify(*ptr);
delete ptr;
std::cout << "Test 2 REF: " << std::endl;
ptr = generate();
identify(*ptr);
delete ptr;
return 0;
}