Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Iteration over class pointers using std::vector

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?

like image 530
Da_Boom Avatar asked Nov 30 '22 00:11

Da_Boom


2 Answers

In C++11:

for (GameObject* gameObject : objects) {
    gameObject->update();
}
like image 159
Jarod42 Avatar answered Dec 24 '22 11:12

Jarod42


You need to dereference the iterator

(*itr)->update();

This is the short way to say:

GameObject* pGameObject = *itr;
pGameObject->update();
like image 45
Cory Kramer Avatar answered Dec 24 '22 12:12

Cory Kramer