What are the difference between a public class member
class data
{
public:
std::list<data> list_of_data;
};
And a method that returns a private member as reference?
class data
{
public:
std::list<data>& get_data()
{ return list_of_data; }
private:
std::list<data> list_of_data;
};
Which one is better?
The question doesn’t make much sense in that form. If you publicly broadcast the fact that in the second case the
list_of_datais indeed a member ofdata(even though it is private), then there’s really no difference.But that’s not what we have private members for. In typical C++ design, in your second variant the outside code is not allowed to use any knowledge about private members of
data. The only thing the outside code has knowledge about is the publicget_data()member. Where thatget_data()goes for the actual data – the outsiders don’t know and don’t care.In this case the difference becomes quite noticeable.
In the first case you are exposing the fact that
list_of_datais physically present as a member of classdata. For example, it immediately means that the lifetime oflist_of_datais the same as lifetime of the correspondingdatainstance. It also means that differentdatainstances have differentlist_of_datamembers.In the second case you are not exposing anything like that. The outside code does not know where the actual
std::list<data>object is located and what’s its lifetime. The outside code does not know whether different instances ofdatawill return different references from theirget_data()members. In order to get answers to these questions the outside users have to pay attention to the intended design of the code, instead of jumping to conclusions by reading the code. And it is a good thing.This is the whole reason we often use accessor functions (even reference-returning ones) instead of exposing data members publicly.