KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I decided to see if assigning a reference to a member would make a member a reference. I wrote the following snippet to test it. There's a simple class Wrapper with an std::string as a member variable. I take take a const string& in the constructor and assign it to the public member variable. Later in the main() method I modify the member variable but the string I passed to the constructor remains unchanged, how come? I think in Java the variable would have changed, why not in this code snippet? How exactly do references work in this case? #include <iostream> #include <string> using namespace std; class Wrapper { public: string str; Wrapper(const string& newStr) { str = newStr; } }; int main (int argc, char * const argv[]) { string str = "hello"; cout << str << endl; Wrapper wrapper(str); wrapper.str[0] = 'j'; // should change 'hello' to 'jello' cout << str << endl; }
Tags (comma-separated)
Save Edits
Cancel