I was told that C++ does not allow 2 references refer to the same object. So I wrote a snippet to verify it:
Code:
class Base{
string& s;
public:
Base(string a):s(a){}
~Base(){cout<<"Base"<<endl;}
};
int main(int argc, char* argv[]){
string b = "asdfa";
string a="abc";
Base x(a);
Base y(b);
y = x;
}
Complier reports error:
main.cc: In member function `Base& Base:
perator=(const Base&)':
main.cc:30: error: non-static reference member `std::string&Base::s', can't use
default assignment operator
This is what I expected: 2 references CAN NOT refer to the same object.
But then I wrote another snippet:
Code:
string a = "abc";
string b = "asdfa";
string& x = a;
string& y = x;
y=x;
cout<<y<<endl;
x[0]='X';
cout<<y<<endl;
It seems that this code DOES work. and both x and y refer to the same string. As you modified x to "Xbc", y's value is also changed. How come?!