Possible Duplicate:
Store two classes with the same base class in a std::vector
I have a Problem with inheritance in C++. Here I wrote a simple code to illustrate my problem:
//Animal.h
class Animal
{
public:
Animal();
~Animal();
virtual const void Eat();
};
//Bear.h
class Bear: public Animal
{
public:
Animal();
~Animal();
virtual const void Eat();
};
//Animal.cpp
const void Animal::Eat() {
}
//Bear.cpp
const void Animal::Eat() {
//Do something
}
Now, in another class I declare a vector that should hold animals, and then I create a Bear
and push it into my vector:
std::vector<Animal> a;
Bear b;
a.push_back(b);
The problem is now, that when I traverse my animal vector and try to call Eat()
, the Eat method of the base class (animal) is called, but not the Bear
Eat
method.
Even trying with dynamic_cast it
does not work: the dynamic_cast
fails
dynamic_cast<Bear*>(&a.at(0));
What am I doing wrong? Is it because I lack copy constructor?