2

I have a vector of that contains objects that have have inherited the pet class (cat,dog,fish etc). They all have a common override function called play() and I want to call that function with the iterators.

I'm getting bunch of errors. I'm not sure if I am creating my for iterators correctly.

code snippet:

void play_pets_x_Times (const std::vector<Pet*>& t, const int16_t x) {

int i=0;
while (i < x) {
   for(std::vector<Pet*>::iterator it = t.begin(); it != t.end(); ++it) {
//error conversion from std::vector<Pet*>....
    it->play();  //error request for member 'play' in....
 }

    i++;
}
}
  • 1
    That should be `const_iterator it`. Better still, just use `for (auto it = t.begin()` and don't fret about the type. – 1201ProgramAlarm Nov 19 '19 at 05:17
  • 3
    Better still, use `for(auto& p : t)` and don't fret about the iterator. And fyi, your original code should have used `(*it)->play()`. The first deref is to acquire the object reference (where the object is `Pet*`, the second via `->` is to deref the ensuing pointer to reach the member function. – WhozCraig Nov 19 '19 at 05:20
  • Thank you! Using auto it = ... fixed the first error. And (*it)->play() fixed my second error. – user10005002 Nov 19 '19 at 05:30
  • 2
    `for (const auto& element : t) { element->play(); }` – Jesper Juhl Nov 19 '19 at 05:35

1 Answers1

3

Iterators are pointer-like objects.

On the other hand, you're storing a pointer in the object, not an actual object.

So, to make a long story short, you have 2 things to dereference, but only dereference 1.

// (*it) dereferences the iterator to get a Pet*, -> dereferences the Pet*
(*it)->play();

That should do the trick.


Nope, I'm wrong. You need a const_iterator instead to be const-correct:

std::vector<Pet*>::const_iterator it = t.begin();
  • That won't 'do the trick' without changing the iterator type to `const_iterator` or better still, eliminating it outright. – WhozCraig Nov 19 '19 at 05:33
  • It isn't necessary to eliminate it outright to "do the trick", though I agree probably better in the long run. Fixed the `const_iterator` issue. –  Nov 19 '19 at 05:39
  • you could use `auto it = t.cbegin()` – Dev Null Nov 19 '19 at 05:51