I am trying to Iterate over a vector using pointers I have a vector called:
std::vector<GameObject*> objects;
and a load of functions like these:
void Game::update()
{
std::vector<GameObject*>::iterator itr;
for( itr = objects.begin();itr < objects.end();++itr)
{
itr->update();//I need to call a abstract function in the GameObject Class
}
}
Game::~Game()
{
delete ball;
delete player;
}
Game::Game()
{
ball = new GOBall(800/2 - GOBall::SIZE/2,600/2 - GOBall::SIZE/2);
player = new GOPlayer(0, 600/2 - GOPlayer::SIZEY/2,ball);
objects.push_back(ball);
objects.push_back(player);
}
As you can see I am trying to iterate in a way that still allows me to call the function and also parse the polymorphistic class into other polymorphistic classes(hence the reason its declared before being parsed into the vector), what I keep getting is error:
C2839: invalid return type 'GameObject *const *' for overloaded 'operator ->'
and error:
C2039: 'update' : is not a member of 'std::_Vector_const_iterator<_Ty,_Alloc>'
which tells me i cant call ball->update()
or player->update()
through the iterator, so how do I do it?
In C++11:
for (GameObject* gameObject : objects) {
gameObject->update();
}
You need to dereference the iterator
(*itr)->update();
This is the short way to say:
GameObject* pGameObject = *itr;
pGameObject->update();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With