c++constructorreferencemember-initialization

Problem while initializing reference variable of class through Member initialization list


code

#include<iostream>
struct A
{
    private:
        
    public:
        int &p,q;
        A(int &k1,int k2):p(k1),q(k2)
        {
            
        }

};

int main()
{
    int x=2;
    A a1(x,3);

    std::cout<<&x<<"\n";
//  std::cout<<&k1<<"\n";    commented out this as it gives error
    std::cout<<&a1.p<<"\n";
    
}

Output

0x6ffe1c
0x6ffe1c

p is referring to k1 and k1 is referring to x.

K1 is going to out of scope right so trying to access it gives error okay. But a1.p actually referring to k1 so it is referring to memory which is not exist. so why accessing a1.p not gives error.


Solution

  • It seems you misunderstand how references work.

    Once you have initialized a reference, you can never access the reference variable itself again. All use of the reference variable will be redirected to the variable being referenced instead.

    So in the A constructor, the variable k1 can never be used, all use of it will be of the x variable in the main function. There can't be a dangling reference with the code as currently shown at the time of writing this answer.

    In short: You can't create a reference of a reference.


    However if you modified the A constructor to take the first argument by value instead of by reference:

    A(int k1, int k2) : p(k1), q(k2) {}
    

    Then that would lead to a dangling reference of the k1 variable.