On Wed, 05 May 2004 13:51:50 +0100, TheFerryman <fe***@onthenet.com> wrote:
How bad is it to include a non const accessor to a container of
objects? For instance
template <class WheelType>
class CarBase
{
typedef std::list<WheelType*> WheelList;
private:
//for the sake of this example, assume there can be any number
//of wheels
WheelList m_Wheels;
//other components
public:
const WheelList& GetWheels()const{return m_Wheels;}
WheelList& GetWheels(){return m_Wheels;}
//other car related methods
};
I think this doesn't look good because I may as well make the
WheelList public... but I hate making member variables public unless
the class is a simple data structure (which this isn't, the real-world
examples are complex)
But if I only have the const accessor how should a client gain access
to the wheels so they can change their properties? (If I create an
iterator class to iterate through the objects how is that any
different to allowing public access)
This thing keeps going around and around my head and I think I'm
starting to obsess on the problem so any help will be greatly
appreciated. What do *you* do in these circumstances?
I think you're having difficulty because of the interface you've chosen. In
a typical collection of some kind, the "get" and "set" functionality isn't
going to be abstracted in terms of getting and putting "the entire
collection", but rather individual elements of the collection. If you were
to separate out "getting" from "setting", then the result of getting could
be a value (rather than a ref), and setting could be sanity-checked. The
way you treat the wheel list doesn't take advantage of any of that; so for
all intents and purposes, you may as well have m_Wheels be public if that's
all the functionality you want.
I think you need to decide whether CarBase is going to concern itself with
individual Wheels or not. If so, then "get" and "set" functionality should
be provided for individual Wheels if you really want CarBase to have some
added value. If not, then WheelList should be a user-defined class in its
own right, perhaps implemented in terms of a list (or not), so that after
obtaining a handle to it from CarBase via GetWheels, the client would still
have to go thorough WheelLists's (presumably safe) interface to munge with
the Wheel List. Make any sense?
-leor
--
Leor Zolman --- BD Software ---
www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html