Is it a good thing to hide pointers members with setters that use references?
class Foo
{
Bar* m_ptr;
public :
void setBar(Bar& bar){m_ptr = &bar;}
};
Or is it preferable to expose the true type of referenced object in the setter (And why) ?
void setBar(Bar* bar){m_ptr = bar;}
In fact, I'm using stl conteners that are not "reference friendly", so I have vectors of pointers as class members but I prefer to deal with methods that takes references. Is it a bad thing to do that?
EDIT :
Stored members are pointers, this example fits better my question :
class Foo
{
std::vector<FooObserver *> m_observers;
public :
Do you prefer this :
void addObserver(FooObserver* obs);
Or this :
void addObserver(FooObserver& obs);
?
In both cases pointers should never be NULL and I assume this is the responsibility of the callers objects.
For me it comes down to the semantics of the type. If the pointer is masking a member that is never intended to be NULL then absolutely use a reference in both the input and output positions. If the value can legally be NULL though then using a pointer is the best approach
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With