user963241
user963241

Reputation: 7048

private class data

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.

Upvotes: 0

Views: 151

Answers (3)

LaszloG
LaszloG

Reputation: 719

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.

Upvotes: 5

Prasoon Saurav
Prasoon Saurav

Reputation: 92924

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?

Upvotes: 0

Naveen
Naveen

Reputation: 73503

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.

Upvotes: 0

Related Questions