views:

135

answers:

4

After reading a description about swapping pointer addresses on Stackoverflow, I have a question about C++ syntax for references.

If you have a function with the following signature:

void swap(int*& a, int*& b)

What is the meaning of int*& ? Is that the address of a pointer to an integer? And furthermore being that it is a pointer reference, why is it not required for them to be initialized as follows?

void swap(int*& a, int*& b) : a(a), b(b) {}

Here's the reference question/answer posting (the answer is the point of interest): Swapping addresses of pointers in c

+1  A: 

It's a reference to an int pointer.

You might find this helpful: Difference between pointer variable and reference variable in c++

Plynx
+3  A: 

A reference to an int pointer. This function would be called as follows:

int* a=...; //points to address FOO
int* b=...; //points to address BAR
swap(a,b);
//a now points to address BAR
//b now points to address FOO
Ken Bloom
+1  A: 

Example that demonstrates how pointer references are used:

int items[] = {42, 43};
int* a = &items[0];
int* b = &items[1];
swap(a, b);
// a == &items[1], b == &items[0]
// items in the array stay unchanged
Chris Jester-Young
+1  A: 

Because swap here is a function, not a class. Your second code snippet is not valid C++ syntax (you are trying to mix function declaration with a class constructor.)

Nikolai N Fetissov
Good catch. I didn't notice the constructor thing in the second snippet of code.
Ken Bloom