Alex Rivera | Logout

Passing by reference to a constructor

Asked 2012-02-29T21:35:54.327
52

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;
}
Edit
Report

1 Answer

6
class Wrapper
{
public:
   string& str;

   Wrapper(string& newStr) : str(newStr) {}
};

Note, you cannot accept a const string& and store it in a string&, you would lose const-correctness in doing so.

answered 2012-02-29T21:43:13.497

Your Answer