Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 560
PaulG Avatar asked Jul 16 '13 14:07

PaulG


People also ask

What is a subclass in C?

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.

How do you tell if an object is a subclass?

isinstance() checks whether or not the object is an instance or subclass of the classinfo.

How do you check if an object is an instance of a class C++?

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.

How can you find out what sub class an object is C#?

We can check the class is a subclass of the specific class or not by using the IsSubclassOf() method of the Type class.


2 Answers

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.

like image 118
Marcin Avatar answered Sep 29 '22 13:09

Marcin


Dog* dog = dynamic_cast<Dog*>(myAnimalPointer);
if (dog == NULL)
{ 
    // This animal is not a dog.
}
like image 27
Aesthete Avatar answered Sep 29 '22 15:09

Aesthete