HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

Are there benefits of passing by pointer over passing by reference in C++?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
benefitspointerareoverreferencetherepassing

Problem

What are the benefits of passing by pointer over passing by reference in C++?

Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?

Example:

func(SPRITE *x);


with a call of

func(&mySprite);


vs.

func(SPRITE &x);


with a call of

func(mySprite);

Solution

A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.

Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:

// Is mySprite passed by value or by reference?  You can't tell 
// without looking at the definition of func()
func(mySprite);

// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);

Code Snippets

// Is mySprite passed by value or by reference?  You can't tell 
// without looking at the definition of func()
func(mySprite);

// func2 passes "by pointer" - no need to look up function definition
func2(&mySprite);

Context

Stack Overflow Q#334856, score: 258

Revisions (0)

No revisions yet.