References

In the book I am reading, it says that the type of a reference must match the type of the object to which the reference refers. If that is true I would expect that the code below would not compile, but it compiles no problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()
{
    const double dval = 3.14;
    const int &ri = dval;

    cout << ri << "\n";

    return 0;
}


if you remove the const from this code snippet, as shown below then compilation fails as expected. Does the rule that the types must match not apply to const references?

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using namespace std;

int main()
{
    double dval = 3.14;
    int &ri = dval;

    cout << ri << "\n";

    return 0;
}
Reading a bit further reveals the following quote which seems to answer my question.

The first exception is that we can initialize a reference to const from any expression that can be converted to the type of the reference. In particular, we can bind a reference to const to a non const object, a literal, or a more general expression:
For the first version of the code ri is bound to a temporary object of type int. The lifetime of the temporary object is extended to the lifetime of the (local const) reference, so the reference does match the type of the object it refers to.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main()
{
    double dval = 3.14;
    const int &ri = dval;

    dval = 9.99;


    cout << ri << '\n';
    cout << dval << '\n';

    std::cout << "Address of dval: " << &dval << '\n';
    std::cout << "Address of (object referenced by) ri: " << &ri << '\n';
}


Non-const references do not extend the lifetime of temporaries.
Last edited on
Topic archived. No new replies allowed.