Passing by reference to a constructor

rcplusplus picture rcplusplus · Feb 29, 2012 · Viewed 47.9k times · Source

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

Answer

111111 picture 111111 · Feb 29, 2012

To assign a reference in a constructor you need to have a reference member

 class A{
     std::string& str;
 public:
     A(std::string& str_)
     :    str(str_) {} 
 };

str is now a reference to the value you passed in. Same applies for const refs

 class A{
     const std::string& str;
 public:
     A(const std::string& str_)
     :    str(str_) {} 
 };

However don't forget that once a reference has been assigned it can not be changed so if assignment requires a change to str then it will have to be a pointer instead.