Parentheses around pointers

Bit of a nooby question here but I was wondering what the parentheses around the pointer in the for loop mean/do. I understand that the * is dereferencing the iterator, but I've never had to put parentheses around a pointer when dereferencing it before.

1
2
3
4
5
  	for (vector<Drawable*>::iterator itrbegin = myvec.begin(),
		itrend = myvec.end(); itrbegin != itrend; ++itrbegin)
	{
		(*itrbegin)->printName();
	}


Thanks in advance.
The angular brackets are used because std::vector is a template and it needs to know what type of iterator to create. http://en.cppreference.com/w/cpp/language/class_template
No. Sorry I didn't make it clear. I was talking about this bit: (*itrbegin)
Oh, my bad. That's done for clarity, so that you know the dereference operators should resolve in that order. First the iterator dereferences to a pointer of type "Drawable" then the -> operator selects the member function from the data that the pointer is pointing at. Otherwise you're looking for a member function that doesn't exist.
Last edited on
Technically speaking, itrbegin is an iterator and not a pointer.

The technical difference between pointers and iterators is that pointers are bult-in into the language (variables that hold a memory address) while iterators are usually coded as classes that overload operator* and operator->, among others (so they can be used as if they were pointers).

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Member_and_pointer_operators

By the way, do not confuse the asterisk symbol (*) when used in declaring a pointer, with when it's an operator.

1
2
3
4
5
6
double *p; // * is not an operator, but part of the pointer declaration
double d;

p = &d;
*p = 10.0; // * is the dereference operator
d = 20.0 * 3.0; // * is the multiplication operator 


Also, the parentheses are used because operator-> has precedence over operator*.

1
2
3
(*itrbegin)->printName(); // not the same as...
*itrbegin->printName(); // which would in fact be the same as...
*(itrbegin->printName());


http://en.cppreference.com/w/cpp/language/operator_precedence

Last edited on
Ah. Thank you very much, guys.
Registered users can post here. Sign in or register to post.