0

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?

msk
  • 131
  • 1
  • 10
  • 4
    This is a design smell. If you need to call subclass-specific methods, it's arguable that you shouldn't be maintaining a vector of pointers-to-superclass. – Oliver Charlesworth Oct 25 '14 at 18:57
  • @Captain Obvlious How so? – msk Oct 25 '14 at 19:04
  • @Oliver Charlesworth Yeah, I understand what you're saying, but I don't know the kind of objects I had to store at compile time, thats why I was using it like this. Also, I use mostly methods from the superclass. – msk Oct 25 '14 at 19:05
  • 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: [Subclass Methods](https://stackoverflow.com/questions/11848800/call-sub-class-method-from-base-class-specific-function) – jProg2015 Oct 25 '14 at 19:08

0 Answers0