tags:

views:

57

answers:

3

should you keep all the data except functions in your class in private section? for example: I have a std::list of integers which i need to access in other class. how would you iterate it and would you really want to keep it private?

Edit:

I'm looking for an individual access to each element in other class.

A: 

Yes, I would keep it private as I don't want anybody to modify it. Then provide a pair of const_iterators to iterate ovet the list.

Naveen
A: 

Yes I would keep it private. Now as we know member functions of a class can access private members of that class so why not iterate over the std::list in the member function itself?

If you need to access it in some other class then you need to create an object of the former class(perform the inserting activity etc by calling some member function on that object) and then call the member function which would perform the iteration activity.

Have I missed something?

Prasoon Saurav
+5  A: 

The real question is why you need to iterate over the list in the 'other class'. If you need to perform a specific operation in the client class you could have other choices:

  1. If you need to perform a well-defined operation (say, computing an average of the values in the list) then you can implement this functionality as a member function of the class that keeps the list.

  2. If you need to perform all kinds of operations on the list then you can build a generic iterator interface, which accepts functions or functors that implement the various operations and return whatever results you need.

Neither of these options require you to expose the list itself.

LaszloG
+1, though iterator interfaces and functors (which implies a visitor pattern) should probably be listed separately...?
Tony
Yes, Tony, you're right. The list was thrown up quickly to distinguish between providing specific operations on the object vs providing generic access to the elements in a more encapsulated way -- but the comment is valid nonetheless.
LaszloG