I have the following code:
struct Y {
string& s1; //string s1; throws no error
Y( string src ) : s1(src) { cout<<"s1: "<<s1<<endl; }
void show(){ cout<<s1<<endl; }
};
int main()
{
Y y1("Krypton");
y1.show(); //run-time error
}
y1.show() should display "Krypton", but I get a runtime error (due to s1 being uninitialized when y1.show() is being called?).
Q1. Why would s1 be uninitialized when it has already been initialized in the constructor initialization list? Q2. Why don't I get the same error if I use string s1; instead of the reference?
Any help would be greatly appreciated.
Regards,
Jay.
You are initializing a reference from a temporary. If you want instances of struct Y
to hold an actual string, rather than just a reference, you need a member variable of type string, not reference to string.
Q1. Why would s1 be uninitialized when it has already been initialized in the constructor initialization list?
It was initialized, but to be a reference to a string that no longer exists.
Q2. Why don't I get the same error if I use string s1; instead of the reference?
If the class contains a string, then it doesn't contain a reference to a string that exists.
What string do you think the reference is a reference to?