Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing non const reference with integer value

Tags:

c++

reference

Please consider this code:

#include <iostream>

using namespace std;

class test
{
    int& ref;
    public:
    test(int i):ref(i)
    {
        cout << "Constructor Called" << endl;
    }
    void p(){ cout<< ref << "\n";}
};

int main()
{
    test obj(5);
    obj.p();

    return 0;
}

Output:

Constructor Called
5

Doubt: How is a non-const reference (ref) being initialized with an integer value (5) here, while the following code fails:

int& r = 5;
like image 388
Sandeep Singh Avatar asked Sep 23 '26 17:09

Sandeep Singh


2 Answers

test's constructor:

test(int i)

takes an int as a parameter by value.

When you initialize the obj object by passing 5 to its constructor, i.e.:

test obj(5);

that constructor's parameter i is set to 5 (i.e.: 5 is copied into i), then the member reference ref is initialized with this parameter in the constructor member initializing list (and not the literal 5 used at constructor call):

test(int i):ref(i)

You have a danging reference: the reference ref outlives the referenced object (i), since the constructor's parameter i no longer exists once the constructor has returned.

like image 160
ネロク・ゴ Avatar answered Sep 25 '26 08:09

ネロク・ゴ


The reference is not being initialized with 5 directly, it is being initialized with the local i. Since i is destroyed upon the exit of the constructor, you are left with a dangling reference, which is a reference that references an object that has gone out of scope. Compilers such as Clang will tell you about this, with a warning that may be something like:

warning: binding reference member 'ref' to stack allocated parameter 'i' [-Wdangling-field]

like image 30
Arnav Borborah Avatar answered Sep 25 '26 06:09

Arnav Borborah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!