I was trying to store some objects in a vector, subclasses from Animal. I structured it, so that i would have a super class, Animal
, which had Reptile
and Mammal
as subclasses. So far, these should be abstract, as I implemented abstract methods on them.
Each one with subclasses, for example, Crocodile
and Lizard
as subclasses of Reptile
, and Dog
and Cat
as subclasses of Mammal
.
I was storing them in a vector, std::vector<Animal*>
to have polymorphism, but I was having problems calling, for example, a Mammal
-specific method, which doesn't make sense having in the Animal
Superclass, because Reptile
is a subclass of it.
std::vector<Animal*> _list_animals;
...
_list_animals[0] = new Dog();
_list_animals[0]->foo(); //foo is a virtual method from Animal, so no problems here
_list_animals[0]->bar(); //bar is a method from `Mammal` only, so it can't be called like this
How could I acess that method, without casting?
Redesign of your code structure so that you don't have this problem is your best choice. But if you insist on doing it this way, see this answer on StackOverflow:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.