example2_type_comparison.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <typeinfo>

class Animal {
public:
    virtual ~Animal() {}
};

class Dog : public Animal {};
class Cat : public Animal {};

void identifyAnimal(Animal* animal) {
    if (typeid(*animal) == typeid(Dog)) {
        std::cout << "This animal is a Dog" << std::endl;
    } else if (typeid(*animal) == typeid(Cat)) {
        std::cout << "This animal is a Cat" << std::endl;
    } else {
        std::cout << "Unknown animal type" << std::endl;
    }
}

int main() {
    Animal* dog = new Dog();
    Animal* cat = new Cat();
    Animal* generic_animal = new Animal();

    identifyAnimal(dog);
    identifyAnimal(cat);
    identifyAnimal(generic_animal);

    delete dog;
    delete cat;
    delete generic_animal;

    return 0;
}
Back to typeinfo