Give references values?

Why is this possible?:

1
2
3
4
5
6
7
8
#include <iostream>

using namespace std;

int main(){
	const int &a = 10; //<- this
	return 0;
}


I thought I understood references but this doesn't make sense to me?!


Edit:

1
2
3
4
5
6
7
8
#include <iostream>

using namespace std;

int main(){
	const int &foo = 10;
	cout << &foo << endl;
	return 0;}

I am setting the reference foo to represent the memory holding 10 but since 10 isnt a variable(it isnt stored) this doesn't make sense to me.
Last edited on
Well, the short answer is that you can do that because the standard says so.

It's equivalent to doing something like this:
1
2
int temp_foo = 10;
const int& foo = temp_foo;


The usefulness of this really isn't apparent there, but one reason this construct exists is to be able to pass in temporaries to functions that expect const references.

1
2
3
4
5
6
7
void foobar(int& a) { }
int main 
{
    int b = 3;
    foobar(b); // OK
    foobar(3); // Error
}

The above foobar(3); won't work because you can't make a temporary become a non-const reference.

But if you change it to
1
2
3
4
5
6
7
void foobar(const int& a) { }
int main 
{
    int b = 3;
    foobar(b); // OK
    foobar(3); // Still OK!
}

Then the function will work, because it allows turning a temporary object (3) into a const reference.

There was a thread like this before, where someone explained it quite well, but I can't find it...
Topic archived. No new replies allowed.