Passing by reference... Stupid Q

Sorry for this question but I can't hold back lol here is some code from the tutorial:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// passing parameters by reference
#include <iostream>
using namespace std;

void duplicate (int& a, int& b, int& c)
{
  a*=2;
  b*=2;
  c*=2;
}

int main ()
{
  int x=1, y=3, z=7;
  duplicate (x, y, z);
  cout << "x=" << x << ", y=" << y << ", z=" << z;
  return 0;
}


Now from what I've read when you define an argument like: int& a, that means the variables will be passed by reference right? So for example when they call duplicate(x,y,z) in this example, wouldn't it pass the memory address of each of those variables? And then when they do the arithmetic in the duplicate function wouldn't that be pointer arithmetic?

I've also seen this:

1
2
3
4
5
6
7

type& name(){

  return *this;

}


Now "this" returns an pointer to the object this function is being executed in right? So *this would be the "value pointed by this"... So why have type&? - Doesn't that mean return the variable by reference?

Anyway, I'm all over the shop here lol At least I feel like I'm making some ground lol

Any help would be awesome,

Nick :)


When you are passing/returning references, there is no special symbol you use to represent you are passing it by reference, you simply pass the object, and the code deals with the reference handling for you. When you are dealing with references to variables, for all syntactical purposes they are basically the same as having the normal object.
I'm sorry, I don't quite understand what you are saying?

Are you saying that the '&' in "int&" is unnecessary?

Nick.
In C++ there are 3 ways to pass a parameter:

- by value: void func( int v ); Called with: func(v);
- by pointer void func( int* v ); Called with: func(&v);
- by reference void func( int& v ); Called with: func(v);

By Value creates a copy of the variable/object for use in the new function. In this case, changes made to v in the function would not change the original variable.

By Pointer passes a pointer to the variable/object. By changing what the pointer points to (ie: *v = 5;) you can change the original variable.

By reference conceptually passes the variable itself. Not a copy, and not a pointer. If you change v in a by-ref function, you are changing the same variable you pass to the function.



If you get down to the nitty-gritty... by pointer and by reference are pretty much the same thing, but have much different syntax. The following two functions are equivilent:

1
2
3
4
5
6
7
8
9
void byref(int& a)
{
  a *= 2;
}

void byptr(int* a)
{
  *a *= 2;
}
Haha thanks Disch! Great answer :)

Nick
Topic archived. No new replies allowed.