Is the reason why I got a garbage value because of the following or am I wrong?
the Other object o passed as an argument to the Inner constructor, goes out of scope after the Inner object has been created, but before the end of the get_a_value member function. Therefore, the reference member m_o in the Inner object becomes a dangling reference, referring to an object that no longer exists.
#include <iostream>
class Other
{
private:
int j = 3;
friend class TEST; //class TEST is a friend of the class Other
};
class TEST
{
private:
int i = 10;
public:
int get_a_value() const //a member function of TEST
{ //member function begins
struct Inner
{
Inner(Other o) : //constructor
/*m_o{ o } it is correct too */ m_o( o )
{
std::cout << "o.j " << o.j << '\n';
std::cout << "m_o.j " << this->m_o.j << '\n';
}
int get_other_value() //other in the name of the member function refers to Other class defined above
{
return this->m_o.j;
}
Other& m_o;
};
Other o; //local variable of member function get_a_value
std::cout << "outside o.j " << o.j << '\n';
Inner i(o); //local variable of member function get_a_value
return i.get_other_value();
}//member function ends
};
int main()
{
TEST t;
std::cout << t.get_a_value() << '\n';
}
The output of code above is :
outside o.j 3
o.j 3
m_o.j 3
623661