#include <iostream>
#include <vector>
#include <typeinfo> // for typeid
class Animal
{
public:
virtual void yawn() = 0;
};
class Cat : public Animal
{
public:
void scratchTheLivingHellOutOfYou()
{
std::cout << "*scratch*\n";
}
virtual void yawn() { std::cout << "meoyawnn!\n"; }
};
class Tiger : public Cat
{
public:
virtual void yawn() { std::cout << "RAWR\n"; }
};
// EXPECTED OUTPUT:
// *scratch*
// RAWR
// *scratch*
// meoyawnn!
int main(int argc, char* argv[])
{
std::vector<Animal*> animals;
animals.push_back(new Cat);
animals.push_back(new Tiger);
std::cout << "USING TYPEID\n\n\n";
// loop through the vector
for(auto i = animals.begin(); i != animals.end(); ++i)
{
Animal* animal = *i;
// if it's a cat
if(typeid(Cat) == typeid(*animal))
{
// make the cat scratch you
Cat* cat = static_cast<Cat*>(animal);
cat->scratchTheLivingHellOutOfYou();
}
// make the animal yawn
animal->yawn();
}
std::cout << "\n\n\nUSING DYNAMIC_CAST\n\n\n";
// loop through the vector
for(auto i = animals.begin(); i != animals.end(); ++i)
{
Animal* animal = *i;
// if it's a cat
if(Cat* cat = dynamic_cast<Cat*>(animal))
{
// make the cat scratch you
cat->scratchTheLivingHellOutOfYou();
}
// make the animal yawn
animal->yawn();
}
return 0;
}