views:

61

answers:

1

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.

A: 

ok, let me take a guess:

"Unhandled exception at 0x65766974 in TestBed.exe: 0xC0000005: Access violation reading location 0x65766974."

it seems that the code pointer is being sent to 0x65766974 ("exception at 0x65766974") but this is not a valid place to be reading, let alone code: ("Access violation reading location 0x65766974", note, the same number)

so is it possible the vtable, or vtable pointer is being corrupted? perhaps the object is being overwritten by a string? as it is being stored in a vector, perhaps you have something overflowing a buffer (maybe a char array?) in the preceding object in the vector, and this is corrupting the next objects vtable pointer?

matt