I have created an abstract base class Animal
which has public virtual abstract method makeSound()
. I created a subclass Cow
which implements Animal.makeSound()
as you would expect (you know... "moo"). And I have a Farm
class which holds a private member variable std::vector<Animal*> animals
. In one of the Farm
methods I iterate over all animals and make them make their sound.
for(unsigned int i = 0; i < animals.size(); i++)
{
animals[i]->makeSound()
}
Unfortunately I get an error
Unhandled exception at 0x65766974 in TestBed.exe: 0xC0000005: Access violation reading location 0x65766974.
Any idea what's going on here?
UPDATE: adding more code per request
class Farm
{
public:
Farm();
virtual ~Farm(void);
void setBarnOnFire();
private:
vector<Animal*> animals;
};
Farm::Farm()
{
animals.push_back(new Dog());
animals.push_back(new Cat());
animals.push_back(new Chicken());
animals.push_back(new Horse());
animals.push_back(new Cow());
}
Farm::setBarnOnFire()
{
for(unsigned int i = 0; i < animals.size(); i++)
{
animals[i]->makeSound()
}
}
Is there something I'm supposed to do to initialize animals
.
RESOLUTION:
So you were all correct. I was accessing memory that I didn't own. But it took me forever to track it down. It was due to a misunderstanding about how object initialization takes place. Basically, in an effort to "initialize" a member variable I was actually overwriting it with a local variable. I then gave the local to all the animals that I created. Later, the animals would try to call the local variable - which no longer existed.