c++oopinheritancepolymorphism

Know the class of a subclass in C++


I haven't done C++ in at least 7 years and am suddenly knee deep in a C++ project. I would like some guidance with the following:

I have a class called Animal, and I have 3 classes that inherit from Animal: Cat, Dog and Bird. I have created a list object and am using it to store type Animal.

This list can contain Cats Dogs and Birds, when I am iterating through this list of Animals, I would like to know the immediate type of each Animal (whether it's a Cat, Dog or Bird).

When I say typeid(animal).name(); it gives me Animal, which is true, but I would like to know what kind of Animal.

Any ideas?? Should I use enums??


Solution

  • You almost certainly don't want to know. What you should do is declare as virtual appropriate methods to interact with these animals.

    If you need to operate on them specifically, you can either use the visitor pattern to pass a visitor object or function the right data in each concrete class. If you insist on having tags (and I emphasise that this is the third choice - the other two solutions will leave your code much cleaner), have a virtual method called classname which returns the type identifier (whether as a string or int or whatever).

    Note also the point about slicing if you have an array of object type, as opposed to pointer type. If you haven't used C++ in 7 years, you may not be aware of the growth of template usage to make the language vastly better. Check out libraries like boost to see what can be done, and how templating allows you to write type-inferred generic code.