Pointers, References and Values by Michael D. Crawford Continued...

When to Pass Pointer Parameters to Functions

Pass a pointer to a function when the object pointed to might not exist.

You generally want to pass pointers to functions for some of the same reasons you want to pass references - to avoid the overhead of copying, and to avoid the slicing problem that occurs when passing base class objects by value.

For the most part you should prefer references to pointers, but use pointers in the case that the object being passed may not always exist - that is, you pass a pointer when you are giving either the address of a real object or NULL.

In this case, it is the responsibility of the recipient function to test the pointer for validity before dereferencing it.

You'll find that this convention is not widely followed. I didn't invent it; I think I picked it up from comp.lang.c++.moderated on the Usenet News.

Another convention which is probably more widely followed has its roots in the original C language - passing a pointer when you want to modify the original, regardless of whether the object is guaranteed to exist. This convention discourages references because of C's strong pass-by-value roots; using references is thought to be confusing. (C programmers usually pass any struct by pointer for efficiency as well. This was the only way to pass structs in the original Kernighan and Ritchie C.)

My suggestion to help resolve the confusion by using the convention that I first saw used in Metrowerks' PowerPlant application framework - indicate the direction of data flow with the name of the formal parameter in the function prototype:

void Foo( const Bar &inParam, Bar &outResult );

A reason for avoiding both pointer and reference parameters is that the object being passed may be held by the caller in a register. Passing a pointer to it requires the register to be stored in or copied to the stack so that its address may be taken. Large objects will never be held in registers but small objects or built in types will often be.

next button previous page contents all programming tips titles

Copyright © 2000, 2001, 2002, 2005 Michael D. Crawford. All Rights Reserved.

One Must Not Trifle With Wizards For It Makes Us Soggy And Hard To Light