First, typeid(a).name()
will return a string that is compiler specific. In my gcc, for example, the returned string would be something totally different. Also, think of a third class that is subclass of Dog. Your typeid(a).name()
would give you "class Chihuahua", which is a dog, but is not "class Dog".
You should use dynamic_cast for querying object type. When you do dynamic_cast<Dog*>(a)
you are asking "can a be correctly casted to Dog?". If yes, you will have a pointer of type Dog*, if not you will have a NULL pointer.
Finally, at class AnimalKingdom
, your vector is not going to allow you to have objects of type Dog. When you create a std::vector<Animal>
, you are creating a vector whose elements are of fixed type sizeof(Animal)
. What you need is to work with pointers. A pointer points to a memory address without forcing this address to be of any size or of the base class.
Just to make it a bit more clear: When you do Animal a;
you are creating a variable that is of the type Animal
and has size sizeof(Animal)
. When you do Animal* a
you are creating an memory address that has the size 4 bytes (or 8 bytes), for any pointer this will have this size. So it is possible that the Animal* points to something different than Animal
, it may point to a subclass of Animal
.
This is the difference between static allocation (fixed size) and dynamic allocation (dynamic size, but note that the pointer has a fixed size).