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.