loop data structure from outside class without allowing modification

Greetings,
i've a class C which contains a list of pointers to a class A.
That list must only be modified by C methods, hence it's private.
Still i'd need to let the user loop through the A items contained in that list.

Is there a way to make the list loop-able but not modifiable which isn't adding a custom iterator to my class C?
What's wrong with exposing a pointer-to-const?
the list is not const, some methods of C can modify it
As someone else said, by returning const reference to that collection. The collection doesn't need to be const, but you can return a const reference to it so that code outside the class cannot modify the collection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <vector>
#include <iostream>

class A {
public:
   int i;
};

class C {
private:
   std::vector<A> a_list;

public:
   void add_to_list(A a) { a_list.emplace_back(a); }
   const std::vector<A>& get_list() { return a_list; }
};

int main() {
   C c;
   c.add_to_list({10});
   c.add_to_list({20});

   for(auto& a : c.get_list()) {
      std::cout << a.i << std::endl;
   }

   // Can't do this, compile error
   c.get_list().push_back({30});

   return 0;
}
Oh didn't think this way to return the list without creating an entire copy of it, thanks! (this doesnt create a copy right? XD)
No, returning a reference to a member variable doesn't create a copy.
Topic archived. No new replies allowed.