-1

So I have a vector declared like so:

vector <Game *> games;

and I have a function in the Game class like so:

public:

    // Rest of .h

    void hello(){
        cout << "hello" << endl;
    }

and I'm trying to iterate over my games vector using an iterator, and call the hello() function each time:

vector <Game *>::const_iterator it_games = games.begin();

for (it_games = games.begin(); it_games != games.end(); it_games++) {
    *it_games->hello();
}

but I keep getting this error when I try to compile:

main.cpp: In function ‘void summary(std::vector<Game*, std::allocator<Game*> >, std::string, std::string, std::string, std::string)’:
main.cpp:56: error: request for member ‘hello’ in ‘* it_games. __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-> [with _Iterator = Game* const*, _Container = std::vector<Game*, std::allocator<Game*> >]()’, which is of non-class type ‘Game* const’

Any idea what's going on/how I can get my desired functionality?

Connor Black
  • 6,921
  • 12
  • 39
  • 70

2 Answers2

2

operator* has lower precedence than operator->. So this:

*it_games->hello();

should be this:

(*it_games)->hello();
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
2

-> has precedence, so the it_games pointer is not dereferenced before hello().

Change

*it_games->hello();

to

(*it_games)->hello();
David G
  • 94,763
  • 41
  • 167
  • 253
smocking
  • 3,689
  • 18
  • 22