mercredi 14 octobre 2020

Use RTTI to get class name from object implementing interface c++

I have a class AnimalInterface in Animal namespace:

namespace Animal
{
    class AnimalInterface
    {
    public:
        AnimalInterface() = default;
        virtual ~AnimalInterface() = default;

        virtual std::string makeSound() = 0;
    };
}

Suppose I have 2 classes implementing from this interface

class Dog : public AnimalInterface
{
public:
    Dog() = default;
    ~Dog() = default;

    std::string makeSound()
    {
        return "Bark";
    }
};

class Cat : public AnimalInterface
{
public:
    Cat() = default;
    ~Cat() = default;

    std::string makeSound()
    {
        return "Meow";
    }
};

Now I have a class from where I call these functions. I would like to be able to get the class names of the animals from the objects using run time type information.

void AnimalSounds
{
    list<unique_ptr<AnimalInterface>> animals;
    animals.push_back(make_unique<Dog>());
    animals.push_back(make_unique<Cat>());

    for (const auto& animal : animals)
    {

        cout << typeid(animal).name() << " makes sound: " << animal->makeSound() << endl;
    }
}

I expect the output to be

Dog makes sound: Bark
Cat makes sound: Meow

Instead, I get the following

class std::unique_ptr<class Animal::AnimalInterface,struct std::default_delete<class Animal::AnimalInterface> > makes sound: Bark
class std::unique_ptr<class Animal::AnimalInterface,struct std::default_delete<class Animal::AnimalInterface> > makes sound: Meow

How do I fix this? Thanks!





Aucun commentaire:

Enregistrer un commentaire