Question about pointers (and iterators)

Can someone explain or provide a link (I couldn't find anything when I did a search), for the reasoning behind using...

(*it)->f()

rather than...

*it->f()

when calling functions using iterators?

Thanks in advance!
Last edited on
(*it) is dereferencing the iterator so that you get the element that the iterator is referring to. If you store pointers in the container this gives you the pointer. When you write (*it)->f() you are calling the function f() on the object that the pointer *it is pointing to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>

class A
{
public:
	void f(){ std::cout << "A::f()\n"; };
};

int main()
{
	A a;
	std::vector<A*> vec{ &a };
	auto it = vec.begin();
	
	(*it)->f();
}


*it->f() is interpreted as *(it->f()). This could work if you are storing class objects in the container instead of pointers and f() returns something that can be dereferenced (e.g. a pointer).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <vector>

class A
{
public:
	A(int value) : value(value) {}
	int* f(){ return &value; }
private:
	int value;
};

int main()
{
	std::vector<A> vec{ A(1024) };
	auto it = vec.begin();
	
	int i = *it->f();
	
	std::cout << i << std::endl;
}
Last edited on
Topic archived. No new replies allowed.