Background info:
I made a class called "fish", which has a display() member function. I also have 2 other classes that are derived from "fish": "pike" and "minnow". I want to make a vector for this, but since it is a vector of pointers I'm a little confused. (I have only been programming for a few months, I am taking an intro to C++ course.)
1 2 3 4 5 6 7 8 9 10 11
int main() {
vector<fish*> fish_vector;
vector<fish*>::iterator i;
pike p1;
fish_vector.push_back(&p1);
while (i != fish_vector.end()) {
(**i).display();
i++;
}
return 0;
}
This program compiles just fine, but when it runs, it hits a segfault before displaying anything. "display()" is just shows what is included in the "fish" class, so (**i) should be a fish.
That ended up working! Also, is there a reason that you used ++i instead of i++? Because I tried compiling it both ways and got a segfault when I used i++...
Actually, i++ and ++i both work with the for loop. I tried using my while loop and initializing i earlier in the code. Now the bigger question is, why do they both work?
++i and i++ accomplish the same thing when used in isolation. ++i tends to be more efficient so it should generally be the default when you don't need i++ behavior.