Search code examples
c++polymorphismdowncast

c++ polymorphism: upcasting/re-downcasting and containers of base class, missing data


I'm trying to fill a vector with derived classes of animals (Dog, Cat, etc). When I take out the contents of the vector, I want to downcast them back to the derived classes.

After doing dog.setLegs(4), I am getting back the correct number of legs with getLegs(). However, after getting back the Animal object from the animals vector and casting that back to type Dog, mydog->getLegs() returns me 0 instead of 4 as I would have expected.

I think I am doing something wrong here but I am not sure what. Can anybody help me with this? Thanks!!

class Animal{
};

class Dog : public Animal {
public:
  void setLegs(int newLegs){legs = newLegs;};
  int getLegs(){return legs;};
protected:
  int legs=0;
};


int main(int argc, char* argv[]){

  Dog dog;
  dog.setLegs(4);
  std::cout<<dog.getLegs()<<std::endl;

  std::vector<Animal> animals;
  animals.push_back(dog);

  Dog *mydog = (Dog*) &(animals[0]);
  std::cout<<mydog->getLegs()<<std::endl;

  return 0;
}

Solution

  • Your std::vector contains only Animals. Putting a subclass of an Animal into the vector "slices" off the subclass, leaving just the Animal in the vector. The subclass is gone. It's no more.

    What you want to do is store pointers to Animal's instead:

     std::vector<Animal *> animals;
    

    So the relevant chunk of your code becomes:

     Dog *mydog = (Dog*)animals[0];
     std::cout<<mydog->getLegs()<<std::endl;