Dereferencing a Vector of Pointers

closed account (jy7fSL3A)
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.

Could you help me with this issue?
i is not initialized to anything, so naturally using it results in odd things happening.

1
2
for ( vector<fish*>::iterator i = fish.begin();  i != fish.end();  ++i )
     (*i)->display() ;
closed account (jy7fSL3A)
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++...
closed account (jy7fSL3A)
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?
Why wouldn't they?

++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.
closed account (jy7fSL3A)
Oh right, I was thinking that you used the ++i in the loop, but the iteration is separate.
Topic archived. No new replies allowed.