Quote:Original post by sheep19
I haven't declared a copy constructor. I thought I had to do it when I use the heap inside the class. (Which I'm not doing.)
But you are:
m_Image = loadImage( "apple.bmp" );
You also delete the image in the class' destructor. This means that the following line:
fruits.push_back( Fruit(200, 200, APPLE) );
will allocate an image, copy a Fruit instance along with a pointer to that image into the vector and then destroy the memory referenced by that pointer leaving a dangling m_Image pointer - hence the crash.
Simply put, your Fruit class isn't copy-safe.
I don't know SDL but a quick google reveals that SDL_Surface has a reference counter which is used for managing situations like this. I'm not sure if you're meant to fiddle with the reference count yourself or whether there's an SDL smart-pointer as part of the library.
The thing to note here is that you're not making proper use of the RAII idiom, which is almost practically required for putting things into a vector. Now the fact is that this Fruit class
can make use of RAII properly (using, for example an SDL smart-pointer). Alternatively you can side-step the issue by using a vector of pointers, as you have done already.
Quote:Why Am I not accessing it correctly? How should it be?
The code you posted was like this:
std::vector<Fruit*> fruits;/* ...*/ for( std::vector <Fruit*>::const_iterator iter = (*fruits).begin(); iter < (*fruits).end(); ++iter )
It ought to be like this:
std::vector<Fruit*> fruits;/* ...*/ for( std::vector <Fruit*>::const_iterator iter = fruits.begin(); iter != fruits.end(); ++iter )
Nothing major, I think you knew this already, I think it was just a casual error.