tags:

views:

65

answers:

3

What is the exact difference between having myMethod(Thing& a) or myMethod(Thing a)? Because later you still ned to use &a if you want the address of the object.. I'm not sure when to use what..

+4  A: 

In the first case you are just passing a reference to a single object, in the second case you are passing a copy of the object.

Paul R
So if it makes a copy.. which constructor does it use then? Do I need to define a copy constructor?
Nils
You need to define a copy constructor if you're not satisfied with what the default copy constructor does. Same question I asked above arises...
conio
A copy constructor is generated by default if you don't provide one and if you don't have a reference as member of the class. Search for infos about the default class member function called "the big four".
Klaim
Copy constructor (as also Constructor and Destructor) is generated automatically if not specified explicitly. Note than by default the copy constructor makes a shallow copy (not deep copy), so your allocated data pointers are just copied as pointers and actual data isn't copied.
Kotti
If you don't define your own copy constructor then the compiler will use an implicit copy constructor, which will of course only perform a shallow copy.
Paul R
Aren't they "Big Three"?
Kotti
this http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) ?
Nils
Yep, but after Klaim's response I thought something like "damn it, I don't know who is the fourth one" :)
Kotti
+1  A: 

Three differences:

  1. With a reference, you have a "shared" instance. So if you modify a you change the original and vice versa.
  2. Performance. With Thing a you invoke the copy constructor. If the copy constructor has to do a lot of things, that could affect how fast the code runs.
  3. A reference is guaranteed to work. If the class has a private copy constructor, you will not be able to do Thing a but you can always do Thing &a.

Finally, if you don't intend for the caller to be able to change the underlying object, you should probably pass by const reference (const Thing &a)

R Samuel Klatchko
A: 

The second one creates a reference to the object, so these two bits of code are identical:

void addOne(int &a){
    a++;
}

void addOne(int *a){
    (*a)++;
}

The difference between with and without the & is that without it, your variable will be copied (and anything you do with it inside the function will be ignored), and with an &, anything you do to the variable inside the function will apply outside of the function as well.

Brendan Long
Shouldn't that be `(*a)++`?
Mike Dinsdale
I'm not sure about the precedence, but I added your suggestion.
Brendan Long
Not exactly. `*a` can be `null` in the second instance, which will cause it to crash.
Mark
You could still pass `*((int*)NULL)` as the argument and get the same behavior (although, it'll crash before the function starts I think, but it's roughly the same behavior, just harder to do).
Brendan Long