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??
Sub Class: The class that inherits properties from another class is called Subclass or Derived Class. Super Class: The class whose properties are inherited by a subclass is called Base Class or Superclass.
isinstance() checks whether or not the object is an instance or subclass of the classinfo.
C++ has no direct method to check one object is an instance of some class type or not. In Java, we can get this kind of facility. In C++11, we can find one item called is_base_of<Base, T>. This will check if the given class is a base of the given object or not.
We can check the class is a subclass of the specific class or not by using the IsSubclassOf() method of the Type class.
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.
Dog* dog = dynamic_cast<Dog*>(myAnimalPointer);
if (dog == NULL)
{
// This animal is not a dog.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With