Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it preferable to store data members as references instead of pointers?

Tags:

People also ask

When you must use a reference instead of a pointer?

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.

Why are references better than pointers?

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.

What is the advantage of using a reference over a raw pointer?

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.

Why are references safer than pointers?

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 NULLs (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?