references question

Discussion in 'C++' started by nvangogh, Mar 17, 2014.

  1. nvangogh

    nvangogh Guest

    According to c++ primer "once initialized, a reference remains bound to
    it's initial object. There is no way to rebind a reference to refer to a
    different object." moreover, "Because references are not objects, we may
    not define a reference to a reference".

    I am confused because this code seems to at least define a reference to
    a reference:

    #include <iostream>

    int main()
    {
    int i = 0, &r1 = i;
    double d = 5.0, &r2 = d;

    r2 = r1;
    std::cout << r2 << std::endl;

    return 0;
    }

    When run this outputs r2 as 0. Why is this?
     
    nvangogh, Mar 17, 2014
    #1
    1. Advertisements

  2. nvangogh schreef op 17-Mar-14 2:47 PM:
    I don't see any reference to a reference in your code.

    It prints 0 because the 'r2 = r1' statement is in effect (after
    following the references) 'd = i;'.

    Wouter van Ooijen
     
    Wouter van Ooijen, Mar 17, 2014
    #2
    1. Advertisements

  3. nvangogh

    Öö Tiib Guest

    Next time please describe what you think that you see. It is impossible
    for us to understand what you think that code does if you do not say it
    out. For me it seems fully normal code and nothing mystical is going on.
    Let me try to describe what I see:
    'i' is int variable object with value 0, 'r1' is reference (alias) of that object.
    'd' is double variable object with value 5.0, 'r2' is reference (alias) of that object.
    Value of 'i' (0) is assigned to 'd'; int is converted to double and 'd' becomes 0.0.
    Value of 'd' (0.0) is output to 'std::cout'.
    I did describe above. Possible cause for your confusion is that you do not
    understand something of what happens. Please describe what it was/is.

    Value of of 'r2' is always value of object what it refers. There are no
    "reference values" unlike with pointers where you have pointer's value and
    value of pointed at object. Therefore you can never take reference to
    reference itself only to object that it refers.
     
    Öö Tiib, Mar 17, 2014
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.