Navigation



6.11 — References

References are a type of C++ variable that act as an alias to another variable. A reference variable acts just like the original variable it is referencing. References are declared by using an ampersand (&) between the reference type and the variable name:

int nValue = 5; // normal integer
int &rnRef = nValue; // reference to nValue

The ampersand in this context does not mean “address of”, it means “reference to”. Let’s take a look at references in use:

nValue = 6; // nValue is now 6
rnRef = 7; // nValue is now 7

cout << nValue; // prints 7
nValue++;
cout << rnRef; // prints 8

Using the address-of operator on a reference returns the address of the value being referenced:

cout << &nValue; // prints 0012FF7C
cout << &rnRef; // prints 0012FF7C

References are implicitly const. Like normal constant objects, references must be given a value upon declaration:

int nValue = 5;
int &rnRef = nValue; // valid reference

int &rnInvalidRef; // invalid, needs to reference something

Furthermore, the reference can not be “redirected” to another variable. Consider the following snippet:

int nValue = 5;
int nValue2 = 6;

int &rnRef = nValue;
rnRef = nValue2; // assigns value 6 to nValue -- does NOT change the reference!

Const references

It is possible to declare a const reference. A const reference will not let you change the value it references:

int nValue = 5;
const int &rnRef = nValue;

rnRef = 6; // illegal -- rnRef is const

You can assign const references to literal values, though there is typically not much need to do so:

const int &rnRef = 6;

Typical use of references

References are typically used for one of two purposes.

First, const references are often used as function parameters, which we will talk about more in the next section on functions. Because const references allow us to access but not change the value of an object, they can be used to give a function access to an object, but give assurance to the caller that the function will not change the object. This helps prevent inadvertent side effects.

Another primary use of references is to provide easier access to nested data. Consider the following struct:

struct Something
{
    int nValue;
    float fValue;
};

struct Other
{
    Something sSomething;
    int nOtherValue;
};

Other sOther;

Let’s say we needed to work with the nValue field of the Something struct of sOther. Normally, we’d access that member as sOther.sSomething.nValue. If there are many separate accesses to this member, the code can become messy. References allow you to more easily access the member:

int &rnValue = sOther.sSomething.nValue;
// rnValue can now be used in place of sOther.sSomething.nValue

The following two statements are thus identical:

sOther.sSomething.nValue = 5;
rnValue = 5;

This can help keep your code cleaner and more readable.

6.12 — References vs. pointers, and member selection
Index
6.10 — Pointers and const

26 comments to 6.11 — References

  • Abhishek

    Hey Alex!

    Is it possible to change the value of a constant reference by changing the value of the original variable?
    Like this:

    int nValue = 5;
    const int &rnRef = nValue;
    
    nValue=7;
    //what will be the value of rnRef now?

    (Please ignore this question if it dosen’t make any sense…….but i hope it does!!)

    • Why not just put this program into your compiler and see what happens? :)

      The answer is yes, you can do this. The fact that we changed the value of nValue does not affect the fact that rnRef is still a const reference to nValue.

      • Abhishek

        “Compilers may go wrong—-Alex wont” :-)

        I was just feeling lazy to do that….. :-)
        I’ll take care to do that myself next time….

      • papagym177

        Alex,
        This is a pretty dumb question, I wonder why no one has asked it before.

        Is there a program that will take an enter snippets and output it to see what they will do?

        I would think you have to put a snippet into a program format to make them work on most compilers

    • In C++ reference means constant reference.
      To the best of my knowledge there is no difference between reference and constant reference.

      • There is a difference between a reference and a const reference. A reference will let you change the value the reference points to, whereas a const reference will not. However, all references are “const” in the sense that you can not change what the reference points to.

    • amjad

      it will be 7

      because the rnRef is constant alias of nValue
      we can not make indirection by rnRef but we can do by nValue

  • Zafer

    I have a question about the statement: “You can assign const references to literal values, though there is typically not much need to do so: const int &rnRef = 6;”

    In another tutorial, I read that a reference variable needs an accessable address. When we declare a reference variable we can only assign something that has a valid address. In other words, the thing we are assigning should be an l-value. However, constant literals do not have predefined memory address therefore cannot be assigned to a reference variable. Please correct me if I’m wrong.

    • This is a very interesting point, and one for which I can not give you a definitive answer. References are typically implemented using pointers, and pointers must point to an address, which implies the other author is correct in that regard. On the other hand, you can experimentally determine that the above code does indeed compile and perform as expected! As you note, there is a seeming inconsistency between these two things.

      My guess is that the compiler promotes the literal 6 to a constant int, and then assigns the reference to that. To see if I could find any evidence of this behavior, I did a simple test:

      const int nRef = 6;
      cout < < &nRef << endl;
      

      On my machine, this prints 0012FF7C

      const int &rnRef = 6;
      cout < < &rnRef << endl;
      

      On my machine, this prints 0012FF78

      With integers being 4 bytes, note that the second example appears to be doing an extra allocation. This certainly lends support to the theory of the literal being promoted to a constant integer.

      • Zafer

        Yes this theory is meaningful. I don’t see however how the second allocation is doing an extra allocation.

        • When you allocate local variables, they are put on the stack. Because of the way stacks work, variables allocated sequentially should be laid out sequentially in memory. For example:

          int x;
          cout < < &x << endl;
          int y;
          cout << &y << endl;
          int z;
          cout << &z << endl;
          

          produces the result:
          0012FF7C
          0012FF78
          0012FF74

          As you can see, the first thing allocated was put in 0012FF7C, the second in 0012FF78, and the third in 0012FF74.

          In the first example above, we allocate one variable (nRef), so it gets allocated to 0012FF7C as we would expect.

          The second example is more interesting. In the second example above, we allocate one reference (rnRef)... When we take the address of a reference, it returns the address of whatever it's referencing (not it's actual address). &rnRef returns 0012FF78, which is the second spot available for allocation. If the thing rnRef is pointing to is in the second spot available for allocation, then what's in the first spot?

          The answer is the reference itself!

          If this is true, then the value at address 0012FF7C (which is where the reference actually lives) should be the address 0012FF78 (which is what the reference is pointing at). If we look at the value in memory address 0012FF7C (using a debugger), we see the decimal value 1245048, which is 0012FF78 in hex.

          So it appears the theory is true. The reference itself is being allocated at memory 0012FF7C. It contains the value 0012FF78, which is what the reference is looking at. Memory 0012FF78 has the value 6. The literal value 6 was given it's own memory address so the reference could point to it.

  • [...] Prev/Next Posts « 6.9 — Dynamic memory allocation with new and delete | Home | 6.11 — References » Monday, July 16th, 2007 at 1:40 [...]

  • el-mudo

    Hey Alex, I would like to thank you for the GREAT tutorial. It’s been very useful for me so far in migrating from C and the simple (very human) language makes it easy to understand even for people with no coding experience

    And good point in the comment up here, i’m pleased to see i’m learning from someone who realy knows what he’s talking about xD

    Now, when somebody asks me where to learn cplusplus, it’s your site I’ll recomend (unfortunately most pleople I know wont be very pleased to have to translate it so then can understand)

    keep the good work!

    (eh, sorry for the bad english)

  • Hi alex,
    doing great job .
    i am fresher attending campus placement.
    please mention which topics in C++ needs to be focussed from interview point of view.
    also post some tricky questions associated with c++ and reference variables which wil be useful for us in interview.

    continue job for welfare of programmers!!!!!!!!!!!!!!!!!!

  • Alex, just another happy and impressed reader of your C++ Tutorials. I’ve been reading the book C++ Primer Plus and it’s a good book, but it sometimes overwhelms the student with too much information on what’s being taught and not on what needs to be learned.

    Your Tutorial is in my opinion far superior to C++ PP. It has really helped me get a better grasp of this language.

    Thank you for bringing the human element to this tutorial and making it easier to understand.

    Note: You should consider making this Tutorial into a book. It’s better than what I’ve seen being offered out in the world.

    Take care and best of luck in your endeavors.

    Dennis

  • afds

    So references are basically like typedefs instead that they don’t change names of data types but of variables.

  • runner

    the following code does not compile:

    int main()
    {
    	int nValue = 4;
    	const int &rfValue = nValue;
    
    	int &rfRef1 = rfValue;
    
    	return 0;
    }

    the error is:
    error C2440: ‘initializing’ : cannot convert from ‘const int’ to ‘int &’

    if the first reference is not const, or both are const, then the code compiles. what is the problem?

    • This doesn’t work because you are trying to set a non-const reference to a const value. Making a variable const essentially means the variable is read-only, and can not be written to. When you assign non-const reference rfRef1 to const reference rfValue, you’re saying that you want to write to a value that was previously defined as const, which is a violation of rfValue’s constness. Const is meant to be a guarantee, not a guideline or something that can be discarded when it’s no longer convenient.

      If you want to modify nValue via reference, assign rfRef1 directly to nValue.

  • [...] 2007 Prev/Next Posts « 6.11 — References | Home | 7.1 — Function parameters and arguments » Tuesday, July 17th, 2007 at [...]

  • Ionamin….

    Ionamin. Ionamin fastin. Search ionamin….

  • [...] ??? ??? ???????? ??? ?? ???? const ??? reference ? ????? ???? ??? ????????? ????? [...]

  • papagym177

    In the code below, nValue is assigned 6 & rnRef is assigner 7. So how do they they get incremented by 1 in the rest of the snippet? This is really confusing.

    nValue = 6; // nValue is now 6
    rnRef = 7; // nValue is now 7

    cout << nValue; // prints 7
    nValue++;
    cout << rnRef; // prints 8

    I would think if you reference something it has the same value as what it references.

You must be logged in to post a comment.