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;
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With