Another tip I suggest is this:
Use links when you can, pointers when you need to. If the object is guaranteed to exist, you should probably use a link. If not, you may have to use a pointer.
Another advantage is that links eliminate ambiguity regarding ownership. As soon as the programmer sees the pointer, they will begin to wonder if they should delete it.
Check this example:
// Wrapper class using a reference because the wrapped object always exists
class wrapper
{
public:
// If the wrapped is guaranteed to exist at creation, do it this way
Wrapper (Wrapped & wrapped): _ wrapped (wrapped) {/ * empty * /}
// put extra methods here.
int getWrappedValue () const {return _wrapped.getValue (); }
private:
Wrapped & _wrapped; // This object always exists and is valid
};
// Wrapper class written to support a possibly non-existent wrapped object.
class wrapper
{
public:
Wrapper (Wrapped * wrapped = 0): _ wrapped (wrapped) {/ * empty * /
void setWrappee (WRappee * wrapped) {_wrapped = wrapped; }
int getWrappedValue () const; // Not making inline - more complex
private:
Wrapped * _wrapped; // Always check pointer before use
};
int Wrapper :: getWrappedValue () const
{
if (_wrapped)
{
return _wrapped-> getValue ();
}
else
{
return -1; // NOTE, this is a contrived example - not getting into exceptions
}
}
dev_dan
source share