References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced but pass by reference.
Reference variables are the alias of another variable while pointer variable are the special type of variable that contains the address of another variable. Reference and pointers both can be used to refer the actual variable they provide the direct access to the variable.
In C++, Reference variables are safer than pointers because reference variables must be initialized and they cannot be changed to refer to something else once they are initialized.
Let's say I have an object Employee_Storage
that contains a database connection data member. Should this data member be stored as a pointer or as a reference?
If I store it as a reference, I
don't have to do any NULL
checking. (Just how important is NULL checking anyway?)
If I store it as a pointer, it's
easier to setup Employee_Storage
(or MockEmployee_Storage
) for the
purposes of testing.
Generally, I've been in the habit of always storing my data members as references. However, this makes my mock objects difficult to set up, because instead of being able to pass in NULL
s (presumably inside a default constructor) I now must pass in true/mock objects.
Is there a good rule of thumb to follow, specifically with an eye towards testability?
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