2

Possible Duplicate: What are the differences between pointer variable and reference variable in C++? How to pass objects to functions in C++?

I am learning about reference parameters and got the following question:

What is the difference between this:

void B(int* worthRef) {
    *worthRef += 1;
}

int main() {
    int netWorth = 55;
    B(&netWorth);
    return 0;
}

And this:

void B(int &worthRef) {
    worthRef += 1;
}

int main() {
    int netWorth = 55;
    B(netWorth);
    return 0;
}
Community
  • 1
  • 1
blaze
  • 2,588
  • 3
  • 32
  • 47

2 Answers2

5

The first one (int *) passes a pointer-to-integer by value; the second (int &) passes an integer by reference. Both methods can be used to implement abstract "reference semantics", but in C++ you should use actual references when possible.

When you use pointers to implement reference semantics, you pass by value a pointer to the object that you want to refer to, and you dereference the pointer to obtain the actual object reference. In C, where you have no references in the language, that's the only way to implement reference semantics, but in C++ you have actual reference types in the language for this purpose.

Note that passing a pointer can be used a little differently from a reference, since you can pass a null pointer to convey additional semantics, and you can also modify the pointer variable (e.g. for using the local copy of the pointer in the callee scope to traverse an array).

But in a nutshell: Use references. Don't use naked pointers in C++. (To implement reference semantics, you use references, and to implement whatever else naked pointers can be (ab)used for, use the appropriate higher-level idiom.) The fundamental problem with naked pointers is that they convey no ownership semantics, and C++ has many far better tools to write maintainable, local and self-documenting code.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

Here you are passing the address of the int:

void B(int* worthRef) {
    *worthRef += 1;
}

The parameter is a pointer. The address passed may be 0 (or NULL). Also used in C. The pointer may altered within B: ++worthRef - why you would prefer that...

Here, the implementation takes the address of the parameter:

void B(int &worthRef) {
    worthRef += 1;
}

The parameter is a C++ reference. The address passed must not be 0, and may not be altered (of course, what it refers to may be altered if not const, as seen in your example). This is the default written style in most C++ circles. Mechanically, a reference is a bit of syntactic sugar, but it is absolutely useful to convey intent and offer guarantees.

Stylistically, some people prefer the former for parameters which may mutate. I use the latter wherever possible (and legal) -- it's more conventional for C++.

justin
  • 104,054
  • 14
  • 179
  • 226