If you can't reference a reference, why does this compile?

Started by
9 comments, last by snk_kid 19 years, 7 months ago

void f2(int& i)
{
}
void f1(int& j)
{
  f2(j);
}
int main()
{
  int k;
  f1(k);
}
j is referencing i which is referencing k.
Not giving is not stealing.
Advertisement
No. Both j and i reference k.
Then how do you get a reference to reference another one?
Not giving is not stealing.
Quote:Original post by thedevdan
Then how do you get a reference to reference another one?


You can't (at least not legally). If you want this concept use a reference to a pointer or a pointer to a pointer instead.
OH!

I had always head that you can't do reference a reference, and that it was a problem. Now I see that what those people were really trying to do was change the second reference to reference something else.

Good, because after I read that I was wondering why all of my code ever compiled when I have several reference "layers" like I showed. Thanks a lot!
Not giving is not stealing.
The thing you have to remember is that a reference is basically an alias to the storage location. It's basically just adding another name to that variable, it's not really creating a new variable.
daerid@gmail.com
This would be what you are thinking of...
void f2(int&* i){}void f1(int& j){  f2(&j);}int main(){  int k;  f1(k);}

error C2528: '<Unknown>' : pointer to reference is illegal

'nuf said!
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
You're thinking of this:
int obj;int& ref = obj;int&& rref = ref; // illegal
typedef int& IntRef;//You can't take a reference to an IntRef.int n = 5;IntRef ref = n;IntRef& rref = ref; //not allowed

This kind of problem crops up, usually in template programming, where you don't know what types you are going to get given.

//general class to make a reference typetemplate<typename T>struct Ref {    typedef T& type;};//specialisation if the type is already a referencestruct <typename T&> Ref {    typedef T& type;};int main() {    int n = 5;    double d = 3.142;    Ref<int>::type nref = n;    Ref<double>::type dref = d;    typedef int& IntRef;    Ref<IntRef>::type nrefRef = n;    return 0;


Not checked but I think that's right.

edit: yep, made a mistake

[Edited by - petewood on September 23, 2004 8:36:34 AM]
Quote:Original post by petewood
*** Source Snippet Removed ***
This kind of problem crops up, usually in template programming, where you don't know what types you are going to get given.

*** Source Snippet Removed ***

Not checked but I think that's right.


I don't think your reference sytax is correct:

It's type& variable = othervariable, not type variable& = &othervariable. Notice the lack of the second &. Actually, your way might be another syntax, but I doubt it. If it is, yell at me.
Not giving is not stealing.

This topic is closed to new replies.

Advertisement