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;
}