Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding pointers with references

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.

like image 282
Laurent Avatar asked Dec 04 '25 16:12

Laurent


1 Answers

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

like image 126
JaredPar Avatar answered Dec 06 '25 06:12

JaredPar